Python 字典

如何创建一个字典:

phonebook = {'foo': '324234', 'bar': '234324'}

person = dict('name' = 'Noah', 'age' = 18)

paddle = dict([('VISCARIA', 'butterfly'), ('CLIPPER WOOD', 'sitiga')])

len(phonebook) # 返回键值对的数量 2

person['name'] # 'Noah'

person['name'] = 'David'

del phonebook['foo'] # 删除键值为'foo'的项

'bar' in phonebook # 检查phonebook中是否有键为'bar'的项   

如何利用zip创建一个字典:

>>> a = [1,2,3]
>>> b = ['a', 'b', 'c', 'd']
>>> zip(a, b)
<zip object at 0x109c60a48>
>>> list(zip(a, b))
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> dict(zip(a,b))
{1: 'a', 2: 'b', 3: 'c'}

字典中键可以自动创建:

car = {}
car['brand'] = 'honda'

字典方法:

clear

d = {}
d['name'] = 'Moose'
d['age'] = 24
d.clear() # 清除字典中所有的项

fromkeys

>>> dict.fromkeys(['apple', 'orange'], 1)    
{'apple': 1, 'orange': 1}

get

>>> d = {}
>>> print(d['name'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'name'

>>> d = {}
>>> print(d.get('name'))
None
>>> print(d.get('name', 'N/A'))
N/A
>>> d['name'] = 'Noah'
>>> print(d.get('name', 'N/A'))
Noah

items / loop

>>> m
{'apple': 1, 'orange': 1}
>>> m.items()
dict_items([('apple', 1), ('orange', 1)])   
>>> for i in m.items():
...     print(i)
... 
('apple', 1)
('orange', 1)

>>> m = {'apple': 1, 'orange': 1}
>>> for k, v in m.items():
...   print('k: {}, v: {}'.format(k, v))
...
k: apple, v: 1
k: orange, v: 1

keys

person = {"age":30,"gender":"male","height":183,"weight":140}
person.keys()

values

person = {"age":30,"gender":"male","height":183,"weight":140}
person.values()

pop

>>> d = {'x':1, 'y':2, 'z':3}
>>> d.pop('y')
2
>>> d
{'x': 1, 'z': 3}    

update

>>> x = {1:'a', 2:'b'}
>>> x
{1: 'a', 2: 'b'}
>>> y = {1:'b', 3:'c'}
>>> x.update(y)
>>> x
{1: 'b', 2: 'b', 3: 'c'}

>>> person = {"name": "noah", "age": 30}
>>> person.update({"age": 32})
>>> person
{'name': 'noah', 'age': 32} 

sorted

d = {1:0,2:3,3:2,5:1}
sorted(d.items(), key=lambda x: x[0]) # sorted by key
sorted(d.items(), key=lambda x: x[1]) # sorted by value
sorted(d.items(), key=lambda x: x[1], reverse=True) # sorted by value desc

Python

这篇文章: 有用 无用
创建 2018-08-05 07:48:13 / 更新 2019-03-26 22:38:51