《Python编程从入门到实践》第六章_字典

print("第六章 字典")
allien_0 = {'color': 'green', 'points': 5}
print("color:" + allien_0['color'])
print("points: " + str(allien_0['points']))  # 通过str函数将数字转化为字符串
#用户信息
user = {'name':'Frank','age':'23','city':'shanghai'}
print(user['name'])
print(user['age'])
print(user['city'])
print("访问字典中的值")
allien_0 = {'color': 'green'}
print(allien_0['color'])
allien_0 = {'color': 'green', 'points': 5}
new_points = allien_0['points']
print("You just earned " + str(new_points) + " points")
print("6.2.2添加键-值对")
allien_0 = {'color': 'green', 'points': 5}
print(allien_0)
allien_0['x_positon'] = 0
allien_0['y_positon'] = 25
print(allien_0)
print("6.2.3创建一个空字典")
allien_0 = {}
allien_0['color'] = 'green'
allien_0['points'] = 5
print(allien_0)
print("6.2.4修改字典中的值")
allien_0 = {'color':'green'}
print("The alien is " + allien_0['color'] + ".")
allien_0['color'] = 'yellow'
print("The alien is now " + allien_0['color'] + ".")
print("6.2.5删除键-值对")
user = {'name':'Frank','age':'23','city':'shanghai'}
print(user)
del user['name']
print(user)
print("6.2.6由类似对象组成的字典")
# 最喜欢的语言
# 确定需要使用多行来定义字典时 在输入左花括号后按回车键 再在下一行缩进四个空格
favorite_languages = {
    'Jen': 'python',
    'Frank': 'c++',
    'Tom': 'JAVA',
    'liu': 'julia',
    }
print(favorite_languages)
print("liu's favorite language is " + favorite_languages['liu'].title() + ".")
print("6.3 遍历字典")
print("6.3.1 遍历所有的键-值对")
favorite_languages = {
    'Jen': 'python',
    'Frank': 'c++',
    'Tom': 'JAVA',
    'Sabar': 'python',
    'Bob': 'ruby',
    }
# 要是for循环遍历字典,可以使用两个变量,用于存储键-值。方法items()返回一个键-值队列表。
for key, value in favorite_languages.items():
    print("key: " + key)
    print("value: " + value)
for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " + language.title() + ".")
print("6.3.2遍历字典中所有键")
favorite_languages = {
    'm': 'java',
    't': 'python',
    'n': 'c++',
    'nn': 'c++',
    }
print(favorite_languages)
for name in favorite_languages.keys():
    print(name.title())
friends = ['m', 'n']
for name in favorite_languages.keys():
    print(name.title())
    if name in friends:
        print("Hi " + name.title() + ", I see your favorite language is " + favorite_languages[name].title() + ".")
if 'dd' not in favorite_languages.keys():
    print("Erin, please take our poll")
print("6.3.3 按顺序遍历字典中的所有键")
for name in sorted(favorite_languages.keys()):
    print(name.title() + ", thank you for taking the poll.")
print("6.3.4遍历字典中所有值")
print("The following languages have been mentioned: ")
for language in favorite_languages.values():
    print(language.title())
print("如上面的运行结果,我们看到了有重复的值,那么如何消除重复的值")
print("The following languages have been mentioned: ")
for language in set(favorite_languages.values()):
    print(language.title())
print("6.4嵌套")
allien_0 = {'color': 'green', 'points': 5}
allien_1 = {'color': 'yellow', 'points': 10}
allien_2 = {'color': 'red', 'points': 15}
alliens = [allien_0, allien_1, allien_2]
for allien in alliens:
    print(allien)

# 创建一个用于存储外星人的空列表
alliens = []

# 创建30个绿色的外星人
for allien_number in range(30):
    new_alien = {'color': 'green', 'points': 5,'speed': 'slow'}
    alliens.append(new_alien)
# 显示前五个外星人
for allien in alliens[:5]:
    print(allien)
print("...")

# 显示创建了多少个外星人
print("Total number of aliens: " + str(len(alliens)))
# 创建一个用于存储外星人的空列表
aliens = []

# 创建30个绿色的外星人
for alien_number in range(0, 30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)
for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
# 显示前五个外星人
for alien in aliens[:5]:
    print(alien)
print("...")
for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
    elif alien['color'] == 'yellow':
        alien['color'] = 'red'
        alien['speed'] = 'fast'
        alien['points'] = 15
# 显示前五个外星人
for alien in aliens[:5]:
    print(alien)
print("...")
print("6.4.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)
favorite_languages = {
    'jen': ['python', 'ruby'],
    'sarah': ['c'],
    'edward': ['ruby', 'go'],
    'phil': ['python', 'haskell'],
    }
for name, languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite language are: ")
    for language in languages:
        print("\t" + language.title())
print("6.4.3在字典里面存储字典")
# 信息字典
user = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
                 },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
             },
        }
for username, user_info in user.items():
    print("\nUsername:", username)
    fullname = user_info['first'] + ' ' + user_info['last']
    location = user_info['location']
    print("\tFull name:" + fullname.title())
    print("\tLocation:" + location.title())
C:\Anaconda3\python.exe H:/python/venv/text
第六章 字典
color:green
points: 5
Frank
23
shanghai
访问字典中的值
green
You just earned 5 points
6.2.2添加键-值对
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_positon': 0, 'y_positon': 25}
6.2.3创建一个空字典
{'color': 'green', 'points': 5}
6.2.4修改字典中的值
The alien is green.
The alien is now yellow.
6.2.5删除键-值对
{'name': 'Frank', 'age': '23', 'city': 'shanghai'}
{'age': '23', 'city': 'shanghai'}
6.2.6由类似对象组成的字典
{'Jen': 'python', 'Frank': 'c++', 'Tom': 'JAVA', 'liu': 'julia'}
liu's favorite language is Julia.
6.3 遍历字典
6.3.1 遍历所有的键-值对
key: Jen
value: python
key: Frank
value: c++
key: Tom
value: JAVA
key: Sabar
value: python
key: Bob
value: ruby
Jen's favorite language is Python.
Frank's favorite language is C++.
Tom's favorite language is Java.
Sabar's favorite language is Python.
Bob's favorite language is Ruby.
6.3.2遍历字典中所有键
{'m': 'java', 't': 'python', 'n': 'c++', 'nn': 'c++'}
M
T
N
Nn
M
Hi M, I see your favorite language is Java.
T
N
Hi N, I see your favorite language is C++.
Nn
Erin, please take our poll
6.3.3 按顺序遍历字典中的所有键
M, thank you for taking the poll.
N, thank you for taking the poll.
Nn, thank you for taking the poll.
T, thank you for taking the poll.
6.3.4遍历字典中所有值
The following languages have been mentioned: 
Java
Python
C++
C++
如上面的运行结果,我们看到了有重复的值,那么如何消除重复的值
The following languages have been mentioned: 
Python
C++
Java
6.4嵌套
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
{'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 number of aliens: 30
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
6.4.2在字典中存储列表
You ordered a thick-crust pizzawith the following toppings:
	mushrooms
	extra cheese

Jen's favorite language are: 
	Python
	Ruby

Sarah's favorite language are: 
	C

Edward's favorite language are: 
	Ruby
	Go

Phil's favorite language are: 
	Python
	Haskell
6.4.3在字典里面存储字典

Username: aeinstein
	Full name:Albert Einstein
	Location:Princeton

Username: mcurie
	Full name:Marie Curie
	Location:Paris

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/weixin_40807247/article/details/82051152
今日推荐