06-Python-字典

1、字典

Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,是一系列键-值(key-value)对,具有极快的查找速度。键-值是两个相关联的值。指定键时,Python会返回与之相关联的值。键-值之间用冒号分割,而键-值对之间用逗号分隔。字典是无序的且键必须唯一

 1 alien = {'color':'green','points':5}  #创建字典
 2  
 3 print(alien['color'])  #访问字典key对应的value
 4 print(alien[points'])
 5 
 6 alien_1 = dict({'color':'red','points':10})  #创建字典
 7 
 8 print(alien_1['color'])
 9 print(alien_1['points'])
10 
11 new_points = alien_1['points]  #可以将value存储在变量中

 

1.1、添加键-值对

字典是一种动态结构,可随时在其中添加键-值对。键-值对的排列顺序和添加顺序无关。

1 alien = {'color':'green','points':5}  #创建字典
2 print(alien)
3 
4 alien['x_position'] = 0  #添加新的键-值对 'x_position':0
5 alien['y_position'] = 25  #添加新的键-值对 'y_position':25
6 print(alien)  #{'color':'green','points':5, 'x_position':0,'y_position':25}

 

1.2、修改字典中的值

 1 alien = {'color':'green'}
 2 print("The alien's color is " + alien['color'] + ".")
 3 
 4 alien['color'] = red
 5 print("The alien's color now is " + alien['color'] + ".")
 6 
 7 #alien举例
 8 alien_1 = {'x_position':0,'y_position':25,'speed':'medium'}
 9 print("Original x_position: " + str(alien_1['x_position']))
10 
11 if alien_1['speed'] == 'slow':
12     x_increment = 1
13 elif alien_1['speed'] == 'medium':
14     x_increment = 2
15 else:
16     x_increment = 3
17 
18 alien_1['x_position'] = alien_1['x_position'] + x_increment
19 
20 print("New x_position: " + str(alien_1['x_position']))

 

1.3、删除键-值对

 1 alien = {'color':'green','points':5}
 2 print(alien)
 3 
 4 #del语句 
 5 del alien['points']  #del语句用来删除键-值对(彻底删除)
 6 print(alien)  #{'color':'green'}
 7 
 8 #pop()方法
 9 alien.pop('points')  #会回显该键对应的值
10 
11 #popitem()方法
12 alien.popitem()  #随机删除,会回显该键对应的值

 

1.4、查找

 1 #in。用来判断键是否存在于字典中,不能判断值
 2 info = {'stu1102': 'LongZe', 'stu1103': 'XiaoZe'}
 3 "stu1102" in info #标准用法,返回值True  
 4 
 5 #get
 6 info.get("stu1102")  #获取该键对应的值 'LongZe'
 7 info.get("stu1105")  #如果该键不存在,则返回None
 8 #
 9 info["stu1102"]  #显示结果同上'LongZe',但是看下面
10 info["stu1105"]  #如果一个key不存在,就报错。而get不会,不存在只返回None

 

1.6、setdefault

 1 info = {
 2     'stu1102': "LongZe",
 4     'stu1103': "XiaoZe",
 5 }
 6 
 7 >>> info.setdefault("stu1106","Alex")
 8 'Alex'
 9 >>> info
10 {'stu1102': 'LongZe', 'stu1103': 'XiaoZe', 'stu1106': 'Alex'}
11 >>> info.setdefault("stu1102","龙泽")
12 'LongZe'
13 >>> info  #值没有发生改变
14 {'stu1102': 'LongZe', 'stu1103': 'XiaoZe', 'stu1106': 'Alex'}

 

1.7、update

1 >>> info
2 {'stu1102': 'LongZe', 'stu1103': 'XiaoZe', 'stu1106': 'Alex'}
3 >>> b = {1:2,3:4, "stu1102":"龙泽"}
4 >>> info.update(b)
5 >>> info  #键的值发生变化
6 {'stu1102': '龙泽', 1: 2, 3: 4, 'stu1103': 'XiaoZe', 'stu1106': 'Alex'}

 

1.8、items()方法

1 >>> info
2 {'stu1102': 'LongZe', 1: 2, 3: 4, 'stu1103': 'XiaoZe', 'stu1106': 'Alex'}
3 >>> info.items()
4 dict_items([('stu1102', 'LongZe'), (1, 2), (3, 4), ('stu1103', 'XiaoZe'), ('stu1106', 'Alex')])  #键-值对成为元组,元组构成列表。

 

1.9、练习题

 1 #用字典来存储一个人的信息,包括姓、名、年龄和居住的城市。
 2 person1 = {'first_name':'san','last_name':'zhang','age':20,'city':'chengdu'}
 3 print(person1)
 4 
 5 #
 6 Numbers = {'a':1,'b':2,'c':3,'d':4,'e':5}
 7 print(Numbers['a'])
 8 print(Numbers['b'])
 9 print(Numbers['c'])
10 print(Numbers['d'])
11 print(Numbers['e'])

 

2、遍历字典

2.1、遍历字典所有的键-值对

 1 user = {
 2     'username':'alex',
 3     'first':'a',
 4     'last':'lex'
 5 }
 6 
 7 for k,v in user.items():  #使用items()方法。
 8     print("key:%s" %k)  #返回顺序可能和存储顺序不一样。
 9     print("value:%s" %v)
10 
11 #
12 favorite_language = {
13     'jen':'python',
14     'sarah':'c',
15     'edward':'ruby',
16     'phil':'c++'
17 }
18 
19 for name,language in favorite_language.items():
20     print("%s's favorite language is %s" %(name.title(),language.title()))

 

2.2、遍历字典所有的键

获取字典元素时,顺序是不可知的。

 1 favorite_language = {
 2     'jen':'python',
 3     'sarah':'c',
 4     'edward':'ruby',
 5     'phil':'c++'
 6 }
 7 
 8 for name in favorite_language.keys():  #keys()方法只取键
 9     print(name.title())
10 
11 '''
12 遍历字典时,会默认遍历所有的键。因此,下面这种写法也是可以获取键的。
13 for name in favorite_language:  
14     print(name.title())
15 '''
16 
17 favorite_language = {
18     'jen':'python',
19     'sarah':'c',
20     'edward':'ruby',
21     'phil':'c++'
22 }
23 
24 friends = ['phil','sarah']
25 for name in favorite_language.keys():
26     if name in friens:
27         print("Hi %s , I see your favorite language is %s!" %(name.title(),favorite_language[name].titile()))

 还可以直接使用keys方法获取所有的键:

1 >>> dic1 = {'a':1,'b':2,'c':3}
2 >>> print(dic1.keys(),type(dic1.keys()))
3 dict_keys(['a', 'b', 'c']) <class 'dict_keys'>

 

2.3、按顺序遍历字典中的所有键

字典总是明确记录着键和值之间的关联关系,但获取字典的元素时,获取顺序是不可预测的。要以特定顺序返回元素,有如下两种方法:

2.3.1、可以在for循环中用sort()方法来获得特定顺序排列的键列表的副本

1 favorite_language = {
2     'jen':'python',
3     'sarah':'c',
4     'edward':'ruby',
5     'phil':'c++'
6 }
7 
8 for name in sorted(favorite_language.keys()):
9     print("%s ,thank you for taking the poll." %name.title())  #Edward..... , Jen......, Phil....... , Sarah.....

 2.3.2、通过字典的keys方法收集键,这些键构成的列表,然后使用列表的sort方法对这些这些key进行排序,最后使用for循环

1 dic1 = {'a':1,'b':2,'c':3}
2 
3 list1 = dic1.keys()  #取出键
4 
5 for key in list1:
6     print(key,"==>",dic1[key]

 

2.4、遍历字典中的所有值

1 favorite_language = {
2     'jen':'python',
3     'sarah':'c',
4     'edward':'ruby',
5     'phil':'c++'
6 }
7 
8 for language in favorite_language.values():  #values()方法提取值
9     print(language.title())

 

3、嵌套

有时候需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。

3.1、字典列表

 1 alien_0 = {'color':'green','points':5}
 2 alien_1 = {'color':'yellow','points':10}
 3 alien_2 = {'color':'red','points':15}
 4 
 5 aliens = [alien_0,alien_1,alien_2]  #将字典放到列表中
 6 
 7 for alien in aliens:
 8     print(alien)  #打印出字典
 9 
10 #
11 aliens=[]  #创建空列表,用于存储外星人
12 
13 for alien_number in range(30):
14     new_alien = {'color':'green','points':5,'speed':'slow'}
15     aliens.append(new_alien)
16 
17 for alien in aliens[ :5]:
18     print(alien)
19 print("......")
20 
21 print("Total number of aliens: %d" %(len(aliens)))

 

3.2、在字典中存储列表

 1 favorite_languages = {
 2     'jen':['python','ruby'],
 3     'sarah':['c'],
 4     'edward':['ruby','go'],
 5     'phil':['python','c++'],
 6     'alex':[]
 7 }
 8 
 9 for name,languages in favorite_languages.items():  #得到的languages是列表
10     if len(languages) > 1:  #如果喜欢的语言多余1门
11         print("%s's favorite languages are :" %(name.title()))
12         for language in languages:  #再用for循环打印列表中的所有元素
13           print("\t%s" %(language.title()))
14     elif len(languages) == 1:  #如果只喜欢一门语言
15         print("%s's favorite language is :" %(name.title()))
16         print("\t%s" %(languages[0].title()))  #因为列表中只有一个元素,因此可以直接使用该方法打印,而不用for循环
17     else:  #没有喜欢的语言
18         print("%s doesn't have any favorite language!" %(name.title()))

 

3.3、在字典中存储字典

因为字典的键是唯一的,因此键不能是字典只有值才能是字典

 1 users = {
 2     'aeinstein':{
 3         'first':'albert',
 4         'last':'einstein',
 5         'location':'princeton'
 6         },
 7     
 8     'mcurie':{
 9         'first':'marie',
10         'last':'curie',
11         'location':'paris'
12         }
13 }
14 
15 for username,user_info in users.items():  #从user字典中取出键-值对,并分别赋值给两个变量
16     print("\nUsername:%s" %username)  
17     
18     Full_name = user_info['first'] + " " +user_info['last']  #访问内部字典,并将值赋值给新变量
19     Location = user_info['location']  #访问内部字典,并将值赋值给新变量
20 
21     print("\tFull name :%s" %Full_name.title())
22     print("\tLocation :%s" %Location.title())

 

posted @ 2017-10-17 17:48  Druid_Py  阅读(307)  评论(0编辑  收藏  举报