[python笔记]5.字典

一.字典

字典可以将相关的信息关联起来

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

输出

green
5

二.使用字典

字典是一系列的键-值对,每个键都与一个值想关联,可以使用键来访问想关联的值,与键值相关的值可以是数字,字符串,列表或者字典,可以将任何对象用作字典中的值
如一中示例'color':'green'就是一个键-值对,最简单的字典只有一个键-值字典中可以包含任意数量的键-值对。

1)访问字典中的值

要获取与键相关联的值,可一次指定字典名和放在方括号内的键
eg1:

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

输出

green

eg2:

aline_0={'color':'green','points':5}
new_points=aline_0['points']
print("You just earned "+str(new_points)+" points!")

输出

You just earned 5 points!

2)添加键-值对

字典可以随时添加键-值对,要添加键-值对,可依次指定字典名,用方括号括起的键和相关联的值。
python不关心键-值对的添加顺序,只关心键和值之间的关联关系
eg1:

aline_0 = {'color':'green','points':5}
print(aline_0)
aline_0['x_position'] = 0
aline_0['y_position'] = 25
print(aline_0)

输出

{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

eg2:

aline_0 = {}#创建空字典
aline_0['color'] = 'green'
aline_0['points'] = 5
print (aline_0)

输出

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

3)修改字典中的值

修改字典中的值,可以依次指定字典名,用方括号括起的键以及与该键相关联的新值。
eg1:

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

输出

The aline is green.
The aline is now yellow.

eg2:

aline_0={'x_position':0, 'y_position':25, 'speed':'medium'}
print("Original x-position " + str(aline_0['x_position']))
if aline_0['speed'] == 'slow':
    x_increment = 1
elif aline_0['speed'] == 'medium':
    x_increment = 2
else:
    x_increment = 3
aline_0['x_position'] = aline_0['x_position'] + x_increment
print("New x_position " + str(aline_0['x_position']))

输出

Original x-position 0
New x_position 2

4)删除键-值对

使用del语句将相应的键-值对彻底删除,必须指定字典名和要删除的键

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

输出

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

ps:存储众多对象的同一种信息,(格式)

favorite_language = {
    'jen': 'python',
    'sarch': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
print(favorite_language)
print("Sarch's favorite language is " + 
	favorite_language['sarch'].title() + 
	'.')

三.遍历字典

1)遍历所有的键-值对

使用for循环遍历,字典的item()方法返回一个键-值对列表,按for循环依次将每个键-值对存储到两个指定的变量中
eg1:

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

使用合适的变量名更容易明白循环的作用,如用name与language代替key与value
eg2:

favorite_language = {
    'jen': 'python',
    'sarch': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name, language in favorite_language.items():
    print(name.title() + 
    "'s favorite language is " + 
    language.title() + ".")

输出

favorite_language = {
    'jen': 'python',
    'sarch': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name, language in favorite_language.items():
    print(name.title() + 
    "'s favorite language is " + 
    language.title() + ".")

2)遍历字典中的所有键

使用字典中的key()方法提取字典中的所有键,存储到变量中
eg:

favorite_language = {
    'jen': 'python',
    'sarch': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name in favorite_language.keys():
    print(name.title())

输出

Jen
Sarch
Edward
Phil

遍历字典时,字典会默认遍历所有键,即上例中如果不使用key方法,结果将不变
eg2:

favorite_language = {
    'jen': 'python',
    'sarch': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name in favorite_language:
    print(name.title())

输出:

Jen
Sarch
Edward
Phil

按顺序遍历字典中的所有键,使用sorted函数(临时排序)
eg2:

favorite_language = {
    'jen': 'python',
    'sarch': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name in sorted(favorite_language.keys()):
    print(name.title()+" ,thank you for talking the poll.")

输出

Edward ,thank you for talking the poll.
Jen ,thank you for talking the poll.
Phil ,thank you for talking the poll.
Sarch ,thank you for talking the poll.

查询一个键是否在字典中
eg3:

favorite_language = {
    'jen': 'python',
    'sarch': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
query_items = ['jen', 'phil']
for query_item in favorite_language.keys():
    if query_item in query_items:
        print("Thank you " + query_item.title())
    else:
        print("Sorry "+query_item.title())

输出

Thank you Jen
Sorry Sarch
Sorry Edward
Thank you Phil

3)遍历字典中的所有值

使用字典中的value()方法,返回一个值列表,不包含任何键
eg:

favorite_language = {
    'jen': 'python',
    'sarch': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for language in favorite_language.values():
    print(language.title())

输出

Python
C
Ruby
Python

该中方法返回的值中不考虑是否有重复元素,如果需要去掉重复元素,需要对包含重复元素的列表调用set(),并使用这些元素创造一个集合

favorite_language = {
    'jen': 'python',
    'sarch': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for language in set(favorite_language.values()):
    print(language.title())

输出

Python
C
Ruby

四.嵌套

1)字典列表

字典作为列表元素
eg1:

aline_0 = {'color': 'green', 'points': 5}
aline_1 = {'color': 'yellow', 'points': 10}
aline_2 = {'color': 'red', 'points': 15}
alines = [aline_0, aline_1, aline_2]
for aline in alines:
    print(aline)

输出

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

使用代码自动生成
eg2:

alines = []
for aline in range(30):
    new_aline = {'color': 'green', 'points': 5, 'speed': 'slow'}
    alines.append(new_aline)
for aline in alines[:5]:
    print(aline)
print("...")
print("Total numbers of alines: " + str(len(alines)))

输出

{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total numbers of alines: 30

2)在字典中存储列表

每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表
eg1:

pizza = {
    'curst': 'thick',
    'toppings': ['mushrooms', 'extra cheese']
}
print("You orderes a " + pizza['curst'] + "-crust pizza " + 
	"with the following toppings:")
for topping in pizza['toppings']:
    print("\t" + topping)

输出

You orderes a thick-crust pizza with the following toppings:
        mushrooms
        extra cheese

eg2:

favorite_languages = {
    'jen': ['python', 'ruby'],
    'sarch': ['c'],
    'eward': ['ruby', 'go'],
    'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite languages are:")
    for language in languages:
        print("\t" + language.title()

输出

Jen's favorite languages are:
        Python
        Ruby

Sarch's favorite languages are:
        C

Eward's favorite languages are:
        Ruby
        Go

Phil's favorite languages are:
        Python
        Haskell

3)在字典中存储字典

eg

#将用户名作为键,将用户信息以字典的形式作为值
users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
    },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
    },
}
for user_name, user_info in users.items():
    print("\nUsername: " + user_name)
    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
发布了101 篇原创文章 · 获赞 1 · 访问量 2998

猜你喜欢

转载自blog.csdn.net/weixin_44699689/article/details/104104454