python字典

#字典
字典 dictionary ,在一些编程语言中也称为 hash , map ,是一种由键值对组成的数据结构。

顾名思义,我们把键想象成字典中的单词,值想象成词对应的定义,那么——

一个词可以对应一个或者多个定义,但是这些定义只能通过这个词来进行查询。

基本操作

空字典

a = {}
type(a)                                   #dict
a = dict()
type(a)                                  #dict

dict
dict

插入键值

a['ones'] = "numbers"
a[1]  = "this is one"

{‘ones’:‘numbers’, 1:‘this is one’}
查看键值

a['ones']

‘this is one’
更新键值

a['ones'] = "this is one, too"
a

{‘ones’: ‘this is one, too’, 1: ‘this is one’}
删除键

del a[1]
a

{‘ones’: ‘this is one, too’}
字典没有顺序
不能使用索引查找键值

a[0]

报错
KeyError Traceback (most recent call last)
in ()
----> 1 a[0]

KeyError: 0

键必须是不可变的类型
出于hash的目的,Python中要求这些键值对的键必须是不可变的,而值可以是任意的Python对象。

synonyms = {}
synonyms['mutable'] = ['changeable', 'variable', 'varying', 'fluctuating',
                       'shifting', 'inconsistent', 'unpredictable', 'inconstant',
                       'fickle', 'uneven', 'unstable', 'protean']
synonyms['immutable'] = ['fixed', 'set', 'rigid', 'inflexible', 
                         'permanent', 'established', 'carved in stone']
synonyms

{‘immutable’: [‘fixed’,
‘set’,
‘rigid’,
‘inflexible’,
‘permanent’,
‘established’,
‘carved in stone’],
‘mutable’: [‘changeable’,
‘variable’,
‘varying’,
‘fluctuating’,
‘shifting’,
‘inconsistent’,
‘unpredictable’,
‘inconstant’,
‘fickle’,
‘uneven’,
‘unstable’,
‘protean’]}

另一个例子:

# 定义四个字典
e1 = {'mag': 0.05, 'width': 20}
e2 = {'mag': 0.04, 'width': 25}
e3 = {'mag': 0.05, 'width': 80}
e4 = {'mag': 0.03, 'width': 30}
# 以字典作为值传入新的字典
events = {500: e1, 760: e2, 3001: e3, 4180: e4}
events

{500: {‘mag’: 0.05, ‘width’: 20},
760: {‘mag’: 0.04, ‘width’: 25},
3001: {‘mag’: 0.05, ‘width’: 80},
4180: {‘mag’: 0.03, ‘width’: 30}}

键(或者值)的数据类型可以不同:

people = [
    {'first': 'Sam', 'last': 'Malone', 'name': 35},
    {'first': 'Woody', 'last': 'Boyd', 'name': 21},
    {'first': 'Norm', 'last': 'Peterson', 'name': 34},
    {'first': 'Diane', 'last': 'Chambers', 'name': 33}
]
people

[{‘first’: ‘Sam’, ‘last’: ‘Malone’, ‘name’: 35},
{‘first’: ‘Woody’, ‘last’: ‘Boyd’, ‘name’: 21},
{‘first’: ‘Norm’, ‘last’: ‘Peterson’, ‘name’: 34},
{‘first’: ‘Diane’, ‘last’: ‘Chambers’, ‘name’: 33}]
使用dict初始化字典
除了通常的定义方式,还可以通过 dict() 转化来生成字典:

inventory = dict(
    [('foozelator', 123),
     ('frombicator', 18), 
     ('spatzleblock', 34), 
     ('snitzelhogen', 23)
    ])
inventory

{‘foozelator’: 123, ‘frombicator’: 18, ‘snitzelhogen’: 23, ‘spatzleblock’: 34}
利用索引更新键值对:

inventory['frombicator'] += 1
inventory

{‘foozelator’: 123, ‘frombicator’: 19, ‘snitzelhogen’: 23, ‘spatzleblock’: 34}
适合做键值的类型
在不可变类型中,整数和字符串是字典中最常用的类型;而浮点数通常不推荐用来做键,原因如下:

data = {}
data[1.1 + 2.2] = 6.6
# 会报错
data[3.3]

KeyError Traceback (most recent call last)
in ()
2 data[1.1 + 2.2] = 6.6
3 # 会报错
----> 4 data[3.3]

KeyError: 3.3

事实上,观察data的值就会发现,这个错误是由浮点数的精度问题所引起的:

data

{3.3000000000000003: 6.6}

有时候,也可以使用元组作为键值,例如,可以用元组做键来表示从第一个城市飞往第二个城市航班数的多少:

connections = {}
connections[(‘New York’, ‘Seattle’)] = 100
connections[(‘Austin’, ‘New York’)] = 200
connections[(‘New York’, ‘Austin’)] = 400

元组是有序的,因此 (‘New York’, ‘Austin’) 和 (‘Austin’, ‘New York’) 是两个不同的键:

print (connections[('Austin', 'New York')])
print (connections[('New York', 'Austin')])

200
400

字典方法

get 方法

之前已经见过,用索引可以找到一个键对应的值,但是当字典中没有这个键的时候,Python会报错,这时候可以使用字典的 get 方法来处理这种情况,其用法如下:

d.get(key, default = None)

返回字典中键 key 对应的值,如果没有这个键,返回 default 指定的值(默认是 None )。

a = {}
a["one"] = "this is number 1"
a["two"] = "this is number 2"
# a["three"]              索引不存在会报错
print (a.get("three"))                #会显示None 也就是default默认值 不会报错

None

a.get("three", "undefined")           #指定默认参数

undefined

#####pop 方法删除元素
pop 方法可以用来弹出字典中某个键对应的值,同时也可以指定默认参数:

d.pop(key, default = None)

删除并返回字典中键 key 对应的值,如果没有这个键,返回 default 指定的值(默认是 None )。

a.pop('two')             # 删除元素并返回删除元素的值
a

‘this is number 2’
{‘one’: ‘this is number 1’}

a.pop("two", 'not exist')                    # 默认返回值

‘not exist’

与列表一样,del 函数可以用来删除字典中特定的键值对,例如:

del a['one']
a

{}

update方法更新字典

之前已经知道,可以通过索引来插入、修改单个键值对,但是如果想对多个键值对进行操作,这种方法就显得比较麻烦,好在有 update 方法:

d.update(newd)

将字典newd中的内容更新到d中去。

person = {}
person['first'] = "Jmes"
person['last'] = "Maxwell"
person['born'] = 1831
print(person)

{‘born’: 1831, ‘last’: ‘Maxwell’, ‘first’: ‘Jmes’}

把’first’改成’James’,同时插入’middle’的值’Clerk’:

person_modifications = {'first': 'James', 'middle': 'Clerk'}
person.update(person_modifications)
print (person)

{‘middle’: ‘Clerk’, ‘born’: 1831, ‘last’: ‘Maxwell’, ‘first’: ‘James’}

in查询字典中是否有该键
barn = {'cows': 1, 'dogs': 5, 'cats': 3}
'chickens' in barn
'cows' in barn

False
True

keys 方法,values 方法和items 方法

d.keys()

返回一个由所有键组成的列表;

d.values()

返回一个由所有值组成的列表;

d.items()

返回一个由所有键值对元组组成的列表;

barn.keys()

[‘cows’, ‘cats’, ‘dogs’]

barn.values()

[1, 3, 5]

barn.items()

[(‘cows’, 1), (‘cats’, 3), (‘dogs’, 5)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值