首页 > 代码库 > Python:字典

Python:字典

字典键的特性:

(1)不允许同一个键出现两次:创建时如果同一个键被赋值两次,后一个值会覆盖前一个
(2)键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行

格式:d = {key1 : value1, key2 : value2 }

字典创建:

#元组列表形式创建字典:
>>> dic1 = dict(([‘ip‘,‘127.0.0.1‘],[‘port‘,‘8080‘]))
>>> dic1
{‘ip‘: ‘127.0.0.1‘, ‘port‘: ‘8080‘}

#列表元组形式创建字典:
>>> dic2 = dict([(‘ip‘,‘192.168.1.1‘),(‘port‘,‘443‘)])
>>> dic2
{‘ip‘: ‘192.168.1.1‘, ‘port‘: ‘443‘}

#表达式方式创建字典: 注意如果是字符串不能用这种方式创建!
>>> dic3 = dict(x=10,y=20,z=30)
>>> dic3
{‘z‘: 30, ‘x‘: 10, ‘y‘: 20}

#**dic3方式创建字典
>>> dic4 = dict(**dic3)
>>> dic4
{‘z‘: 30, ‘x‘: 10, ‘y‘: 20}

#fromkeys方式创建字典: 创建一个默认字典,字典中元素具有相同的value值
>>> dic5 = {}.fromkeys((‘x‘,‘y‘),100)
>>> dic5
{‘x‘: 100, ‘y‘: 100}
>>> dic6 = {}.fromkeys(‘x‘,‘y‘)
>>> dic6
{‘x‘: ‘y‘}
>>> dic7 = {}.fromkeys([‘x‘,‘y‘])
>>> dic7
{‘x‘: None, ‘y‘: None}
>>> dic8 = {}.fromkeys(‘abcd‘,‘1‘)
>>> dic8
{‘b‘: ‘1‘, ‘c‘: ‘1‘, ‘a‘: ‘1‘, ‘d‘: ‘1‘}

字典访问:

dict1 = {Name: Runoob, Age: 7, Class: First} print ("dict[‘Name‘]: ", dict[Name])print ("dict[‘Age‘]: ", dict[Age])

输出结果:

dict1[Name]: Runoobdict1[Age]: 7

字典遍历:

>>> dict = {ip:127.0.0.1,port:80}>>> for i in dict:    print(dict[%s]=%s %(i,dict[i]))

输出结果:

dict[port]=80dict[ip]=127.0.0.1

修改字典:

dict1 = {Name: Runoob, Age: 7, Class: First}dict1[Age] = 8; # 更新 Agedict1[School] = "菜鸟教程" # 添加新信息print ("dict[‘Age‘]: ", dict[Age])print ("dict[‘School‘]: ", dict[School])

输出结果:

dict1[Age]: 8dict1[School]: 菜鸟教程

字典删除:

>>> dict1 = {Name: Runoob, Age: 7, Class: First}>>> dict1.pop(Age)   #删除某个键值>>> dict1{Class: First, Name: Runoob}>>> del dict1[Name]   #删除某个键值>>> dict1{Class: First}>>> dict1.clear()   #清空字典>>> dict1{}>>> del dict1   #删除整个字典>>> del dict1>>> dict1Traceback (most recent call last):  File "<pyshell#96>", line 1, in <module>    dict1NameError: name dict1 is not defined

字典内置函数:

len(dict)  #计算字典元素个数,即键的总数str(dict)  #输出字典以可打印的字符串表示>>> dict = {Name: Runoob, Age: 7, Class: First}>>> str(dict)"{‘Name‘: ‘Runoob‘, ‘Class‘: ‘First‘, ‘Age‘: 7}".clear()  #删除字典内所有元素.copy()  #返回一个字典的浅复制.fromkeys()  #创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值.get(key,default=None)  #返回指定键的值,如果值不在字典中返回default值.items()  #以列表返回可遍历的(键,值)元组数组.keys()  #以列表返回一个字典所有的键>>> d1 = {addr:{ip:127.0.0.1,port:80},msg:18}>>> d1.keys()dict_keys([msg, addr]).values()  #以列表返回字典中的所有值>>> d1 = {addr:{ip:127.0.0.1,port:80},msg:18}>>> d1.values()dict_values([19, {ip: 127.0.0.1, port: 80}]).setdefault(key, default=None)  #和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default.update(dict2) #把字典dict2的键/值对更新到dict里>>> d1 = {addr:{ip:127.0.0.1,port:80},msg:18}>>> d1.update({msg:19})>>> d1{msg: 19, addr: {ip: 127.0.0.1, port: 80}}
例:>>> questions = [name, quest, favorite color]>>> answers = [lancelot, the holy grail, blue]>>> for q, a in zip(questions, answers):...     print(What is your %s? It is %s. %(q, a))        #print(‘questions[%s] = answers[%s]‘ %(q,a))输出结果:What is your name? It is lancelot.What is your quest? It is the holy grail.What is your favorite color? It is blue.#questions[name] = answers[lancelot]#questions[quest] = answers[the holy grail]#questions[favorite color] = answers[blue]
例:>>> for i in reversed(range(1, 10, 2)):        print(i)输出结果:97531
例:>>> l1=[1,2,3]>>> l2=[a,b,c]dict(map(lambda x,y:[x,y], l1,l2))输出结果:{1: a, 2: b, 3: c}

 

Python:字典