欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python 字典dict使用介绍

程序员文章站 2022-06-13 19:19:06
python字典的创建 方法一: >>> blank_dict = {} >>> product_dict = {'mac...

python字典的创建

方法一:

>>> blank_dict = {}
>>> product_dict = {'mac':8000,'iphone':5000, 'ipad':4000, 'mp3': 300}
>>> product_dict
{'ipad': 4000, 'mac': 8000, 'iphone': 5000, 'mp3': 300}
>>> blank_dict,product_dict
({}, {'ipad': 4000, 'mac': 8000, 'iphone': 5000, 'mp3': 300})

方法二:
从python 2.2版本开始

>>> fdict = dict((['www','www.linuxeye.com'],['blog','blog.linuxeye.com']))
>>> fdict
{'blog': 'blog.linuxeye.com', 'www': 'www.linuxeye.com'}

方法三:
从python 2.3版本开始, 可以用一个很方便的内建方法fromkeys() 来创建一个”默认”字典, 字典中元素具有相同的值 (如果没有给出, 默认为none):

>>> fk_dict = {}.fromkeys(('a','b'),'linuxeye')
>>> fk_dict
{'a': 'linuxeye', 'b': 'linuxeye'}
>>> fk2_dict = {}.fromkeys(('yeho','python'))
>>> fk2_dict
{'python': none, 'yeho': none}
>>> fk3_dict = {}.fromkeys('yeho','python')
>>> fk3_dict
{'y': 'python', 'h': 'python', 'e': 'python', 'o': 'python'}

python字典查、增、删、改

>>> product_dict = {'mac':8000,'iphone':5000, 'mp3': 300}
>>> product_dict['iphone']
5000
>>> product_dict['ipad'] = 4000 #增
>>> product_dict
{'ipad': 4000, 'mac': 8000, 'iphone': 5000, 'mp3': 300}
 
>>> product_dict.keys() #查看索引
['ipad', 'mac', 'iphone', 'mp3']
>>> product_dict.values() #查看值
[4000, 8000, 5000, 300]
>>> product_dict.items()
[('ipad', 4000), ('mac', 8000), ('iphone', 5000), ('mp3', 300)]
>>> for product,price in product_dict.items():
...  print product,price
...
ipad 4000
mac 8000
iphone 5000
mp3 300
>>> product_dict.has_key('iphone') #判断key是否存在
true
>>> product_dict.has_key('itouch')
false
 
>>> product_dict.pop('mac') #删除指定key和value
 8000
 >>> product_dict
 {'ipad': 4000, 'iphone': 5000, 'mp3': 300}
 >>> product_dict.popitem() #删除第一个key和value
 ('ipad', 4000)
 >>> product_dict
 {'iphone': 5000, 'mp3': 300}
 
 >>> product_dict = {'iphone': 5000, 'mp3': 300}
 >>> del product_dict['iphone'] #用del函数删除指定key和value
 >>> product_dict
 {'mp3': 300}
 >>> product_dict['mp3'] = 299 #改
 >>> product_dict
 {'mp3': 299}
 >>> product_dict.clear() #清空字典内容(空字典)
 >>> product_dict
 {}
 >>> del product_dict #删除字典
 >>> product_dict = {'mp3': 300}
 >>> del product_dict #已删除报错
 traceback (most recent call last):
  file "<stdin>", line 1, in <module>
 nameerror: name 'product_dict' is not defined