Python 字典dict

Python 字典dict,第1张

Python 字典dict

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','linuxeye.com']))
>>> fdict
{'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 "", line 1, in 
 NameError: name 'product_dict' is not defined
Tue Oct 15 21:54:26 CST 2013

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/3012696.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-28
下一篇 2022-09-28

发表评论

登录后才能评论

评论列表(0条)

保存