Heim  >  Artikel  >  Backend-Entwicklung  >  Python字典操作简明总结

Python字典操作简明总结

WBOY
WBOYOriginal
2016-06-06 11:24:371278Durchsuche

1.dict()创建字典

代码如下:


>>> fdict = dict((['x', 1], ['y', 2]))
>>> fdict
{'y': 2, 'x': 1}


2.fromkeys() 来创建一个"默认"字典,字典中元素具有相同的值

代码如下:


>>> ddict = {}.fromkeys(('x', 'y'), -1)
>>> ddict
{'y': -1, 'x': -1}


3.遍历字典
使用keys()遍历

代码如下:


>>> dict2 = {'name': 'earth', 'port': 80}
>>>
>>>> for key in dict2.keys():
... print 'key=%s, value=%s' % (key, dict2[key])
...
key=name, value=earth
key=port, value=80


使用迭代器遍历

代码如下:


>>> dict2 = {'name': 'earth', 'port': 80}
>>>
>>>> for key in dict2:
... print 'key=%s, value=%s' % (key, dict2[key])
...
key=name, value=earth
key=port, value=80


4.获得value值

字典键加上中括号来得到

代码如下:


>>> dict2['name']
'earth'


5.成员操作符:in或not in
判断键是否存在

代码如下:


>>> 'server' in dict2 # 或 dict2.has_key('server')
False


6.更新字典

代码如下:


>>> dict2['name'] = 'venus' # 更新已有条目
>>> dict2['port'] = 6969 # 更新已有条目
>>> dict2['arch'] = 'sunos5'# 增加新条目


7.删除字典

代码如下:


del dict2['name']    ​#删除键为“name”的条目
dict2.clear()    ​#删除 dict2 中所有的条目
del dict2     ​#删除整个 dict2 字典
dict2.pop('name')    ​#删除并返回键为“name”的条目


8.values()返回值列表 

代码如下:


>>>
>>> dict2.values()
[80, 'earth']


9.items()返回(键,值)元组列表 

代码如下:


>>> dict2.items()
[('port', 80), ('name', 'earth')]

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn