Python学习笔记_Day6 字典

什么是字典

在python中,字典是一系列键——值对。每个键都与一个值相关联,可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何python对象用作字典中的值。
在python中,字典用放在花括号{}中的一系列键——值对表示:

alien_0 = {'color': 'green', 'points': 5}

在字典中,你想存储多少个键——值对都可以。

访问字典中的值

alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])#将返回与键color相关联的值

输出为:

green

如何添加键——值对

字典是一种动态结构,可随时在其中添加键——值对。

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)

alien_0['x_position'] = 0#添加一对键值对
alien_0['y_position'] = 25#添加一对键值对
print(alien_0)

输出为:

{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
  • 注意:键——值对的排列顺序与添加顺序不同,python不关心键——值对的添加顺序,而只关心键和值之间的关联关系。

修改键——值对

alien_0 = {'color': 'green', 'points': 5}
alien_0['color'] = 'yellow'#将color键的值改为yellow

删除键——值对

对于字典中不再需要的信息,可使用del语句将相应的键——值对彻底删除。使用del语句时,必须指定字典名和要删除的键。

alien_0 = {'color': 'green', 'points': 5}
del alien_0['points']#删除键points

遍历字典

1、遍历所有的键——值对

user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }
    
for key, value in user_0.items():
	print("\nkey: " + key)
	print("value: " + value)

输出为:


key: username
value: efermi

key: first
value: enrico

key: last
value: fermi

items()方法返回一个键——值对列表,然后用for循环依次将每个键——值对存储到指定的两个变量中。

  • 注意,在遍历字典时,键——值对的返回顺序也与存储顺序不同。

遍历字典中的所有键

使用方法keys()可以遍历所有的键。

user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }
    
for key in user_0.keys():#遍历所有的键
	print(key)
  • 遍历字典时,会默认遍历所有的键。若将上面代码中的
for key in user_0.keys():

改为:

for key in user_0:

结果是一样的。

按顺序遍历字典中的键

可使用方法sorted()来获得按特定顺序排列的键列表的副本:

user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }
    
for key in sorted(user_0.keys()):#获取已排序键列表
	print(key)

输出为:

first
last
username

遍历字典中的所有值

可使用方法values()。
这种做法,会提取字典中所有的值,不会考虑是否重复。
为剔除重复项,可使用集合(set),集合类似于列表,但每个元素都必须是独一无二的。

favorite_language = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
    
print("The following languages have been mentioned:")
for language in set(favorite_language.values()):
	print(language.title())

输出为:

The following languages have been mentioned:
C
Python
Ruby

嵌套

将一系列字典存储在列表中,或者将列表作为值存储在字典中,这称为嵌套。
可以“在列表中嵌套字典”“在字典中嵌套列表”“在字典中嵌套字典”。
1、字典列表

alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]#字典列表

2、在字典中存储列表

#存储所点比萨的信息
pizza = {
    'crust' :'thick',
    'toppings': ['mushrooms', 'extra cheese'],#配料列表
    }

4、在字典中存储字典
如果网站有多个用户,而每个用户都拥有几种不同的信息。

users = {#users字典
    'aeinstein': {#用户信息的字典
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
	    },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
        },
    }
	
for username, user_info in users.items():
	print("\nUsername: " + username)
	full_name = user_info['first'] + ' ' + user_info['last']
	location = user_info['location']
	
	print("\tFull name: " + full_name.title())
	print("\tLocation: " + location.title())

猜你喜欢

转载自blog.csdn.net/weixin_44123362/article/details/89165861