python字典的基本用法总结#附有实例

字典是另一种可变容器模型,且可存储任意类型对象
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
键必须是唯一的,但值则不必,
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
下面为对字典的基本用法:

一:访问字典中的值

方括号指定键

aliens = {'color': 'green'}
print(aliens['color'])

结果:
green

二:添加键-值对

字典是一种动态结构,可随时在其中添加键-值对
依次指定字典名,用方括号括起的键和相关联的值

aliens = {'color': 'green', 'points': 5}
print("添加键-值对前:" + str(aliens))
aliens['x_position'] = 0
aliens['y_position'] = 25
print("添加键-值对后" + str(aliens))

结果:
添加键-值对前:{'color': 'green', 'points': 5}
添加键-值对后{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

三:创建一个空字典

aliens = {}
aliens['color'] = 'green'
aliens['points'] = 5
print(aliens)

结果:
{'color': 'green', 'points': 5}

四:修改字典中的值

指定字典名,用方括号括起的键以及与该键相关联的新值

aliens = {'color': 'green'}
print("The alien is " + aliens['color'] + '.')
aliens['color'] = 'yellow'
print('The alien is now ' + aliens['color'] + '.')

结果:
The alien is green.
The alien is now yellow.

五:删除键-值对

使用del 语句指定字典名和要删除的键

aliens = {'color': 'green', 'points': 5}
print(aliens)
del aliens['points']
print(aliens)

结果:
{'color': 'green', 'points': 5}
{'color': 'green'}

六:字典遍历

6.1. 遍历字典中的键-值对

使用字典方法items,它将返回一个键-值列表

person = {'first_name': 'chen', 'last_name': 'mc', 'age': 25, "city": 'beijing'}
print("person: " + str(person.items()))
for k, v in person.items():
    print("\nkey: " + k)
    print("value: " + str(v))

结果:
person: dict_items([('first_name', 'chen'), ('last_name', 'mc'), ('age', 25), ('city', 'beijing')])
key: first_name
value: chen

key: last_name
value: mc

key: age
value: 25

key: city
value: beijing

6.2 遍历字典中的所有键

使用方法keys(),它将返回一个键列表

person = {'first_name': 'chen', 'last_name': 'mc', 'age': 25, "city": 'beijing'}
print("person-keys: " + str(person.keys()))

结果:
person-keys: dict_keys(['first_name', 'last_name', 'age', 'city'])

可以使用sorted对返回的键列表进行临时排序

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
    print(name.title() + ', thank you for taking the poll.')

结果:
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.

6.3. 遍历字典中的所有值

使用方法values(),它将返回一个值列表,而不包含任何键

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

结果:
The following languages have been mentioned:
Python
C
Ruby
Python

剔除字典重复的键或者值,可以使用集合set函数,使每个元素都是独一无二的

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

结果:
The following languages have been mentioned:
C
Ruby
Python

七:字典嵌套

7.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]
for alien in aliens:
    print(alien)

结果:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

7.2 在字典中存储列表

pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# 概述所点的比萨
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the following toppings:")
for topping in pizza['toppings']:
    print("\t" + topping)

结果:
You ordered a thick-crust pizza with the following toppings:
	mushrooms
	extra cheese

7.3 在字典中存储字典

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())

结果:
Username: aeinstein
	Full name: Albert Einstein
	Location: Princeton

Username: mcurie
	Full name: Marie Curie
	Location: Paris
发布了45 篇原创文章 · 获赞 38 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/muchong123/article/details/104728004
今日推荐