Home  >  Article  >  Backend Development  >  Python 字典dict使用介绍

Python 字典dict使用介绍

WBOY
WBOYOriginal
2016-06-10 15:18:381129browse

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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn