02.10-dictionaries
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[1]['first']
'Woody'
inventory = dict(
[('foozelator', 123),
('frombicator', 18),
('spatzleblock', 34),
('snitzelhogen', 23)
])
inventory
{'foozelator': 123, 'frombicator': 18, 'snitzelhogen': 23, 'spatzleblock': 34}
update
方法更新字典
之前已经知道,可以通过索引来插入、修改单个键值对,但是如果想对多个键值对进行操作,这种方法就显得比较麻烦,好在有 update
方法:
`d.update(newd)`
将字典newd
中的内容更新到d
中去。
person = {}
person['first'] = "Jmes"
person['last'] = "Maxwell"
person['born'] = 1831
print (person)
{'first': 'Jmes', 'last': 'Maxwell', 'born': 1831}
把’first’改成’James’,同时插入’middle’的值’Clerk’:
person_modifications = {'first': 'James', 'middle': 'Clerk'}
person.update(person_modifications)
print (person)
{'first': 'James', 'last': 'Maxwell', 'born': 1831, 'middle': 'Clerk'}
keys
方法,values
方法和items
方法
`d.keys()`
返回一个由所有键组成的列表;
`d.values()`
返回一个由所有值组成的列表;
`d.items()`
返回一个由所有键值对元组组成的列表;
barn = {'cows': 1, 'dogs': 5, 'cats': 3}
barn.keys()
dict_keys(['cows', 'dogs', 'cats'])
barn.values()
dict_values([1, 5, 3])
barn.items()
dict_items([('cows', 1), ('dogs', 5), ('cats', 3)])
字典方法
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"]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-126-8a5f2913f00e> in <module>()
----> 1 a["three"]
KeyError: 'three'
改用get方法:
print (a.get("three"))
None
指定默认值参数:
a.get("three", "undefined")
'undefined'
pop
方法删除元素
pop
方法可以用来弹出字典中某个键对应的值,同时也可以指定默认参数:
`d.pop(key, default = None)`
删除并返回字典中键 key
对应的值,如果没有这个键,返回 default
指定的值(默认是 None
)。
a
{'one': 'this is number 1'}
弹出并返回值:
a.pop("two")
'this is number 2'
a
{'one': 'this is number 1'}
弹出不存在的键值:
a.pop('two', 'not exist')
'not exist'
a.pop('two')
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-141-290215c7fe57> in <module>()
----> 1 a.pop('two')
KeyError: 'two'
a.pop('two', 'not exist')
'not exist'
与列表一样,del
函数可以用来删除字典中特定的键值对,例如:
del a["one"]
a
{}