user_0 = {
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
list_1 = user_0.items()
list(list_1)
结果:
Out[2]: [('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
for k,v in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
结果:
Key: last
Value: fermi
Key: last
Value: fermi
Key: last
Value: fermi
favorite_languages = {
'jen':'python',
'sarah':'c',
'edwaid':'ruby',
'phil':'python',
}
for name,language in favorite_languages.items():
print(name.title() + "'s favorite languages is " +
language.title() + ".")
结果:
Jen's favorite languages is Python.
Sarah's favorite languages is C.
Edwaid's favorite languages is Ruby.
Phil's favorite languages is Python.
favorite_languages = {
'jen':'python',
'sarah':'c',
'edwaid':'ruby',
'phil':'python',
}
for name in favorite_languages.keys():
print(name.title())
# 这四行代码等价
for name in favorite_languages:
print(name.title())
结果:
Jen
Sarah
Edwaid
Phil
names = []
names_1 = list(favorite_languages.keys())
for name in favorite_languages:
t_names = name
names.append(t_names)
print(name.title())
print(names)
print(names_1)
结果:
Jen
Sarah
Edwaid
Phil
['jen', 'sarah', 'edwaid', 'phil']
['jen', 'sarah', 'edwaid', 'phil']
favorite_languages = {
'jen':'python',
'sarah':'c',
'edwaid':'ruby',
'phil':'python',
}
friends = ['phil','sarah']
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() + "!")
结果:
Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edwaid
Phil
Hi Phil, I see your favorite language is Python!
favorite_languages = {
'jen':'python',
'sarah':'c',
'edwaid':'ruby',
'phil':'python',
}
if 'erin' not in favorite_languages.keys():
print("Erin,please take our poll!")
结果:
Erin,please take our poll!
favorite_languages = {
'jen':'python',
'sarah':'c',
'edwaid':'ruby',
'phil':'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
结果:
Edwaid, 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.
favorite_languages = {
'jen':'python',
'sarah':'c',
'edwaid':'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
print("The following languages have been mentioned: ")
for language in set(favorite_languages.values()):
print(language)
list_languages = list(favorite_languages.values())
print(type(list_languages))
print(list_languages)
结果:
The following languages have been mentioned:
python
ruby
c
<class 'list'>
['python', 'c', 'ruby', 'python']
python,c,ruby,python
value = favorite_languages.values()
print(",".join(i for i in value))
结果:
python,c,ruby,python
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}
aliens = []
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
# 显示前5个外星人
for alien in aliens[:5]:
print(alien)
print(".......")
结果:
{'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'}
.......
print("\nTotal number of aliens: " + str(len(aliens)))
结果:
Total number of aliens: 30
aliens = []
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[:5]:
print(alien)
print(".......")
结果:
{'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'}
.......
aliens = []
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[: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[:10]:
print(alien)
print(".......")
结果:
{'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': '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'}
.......
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
favorite_languages = {
'jen':['python','ruby'],
'sarah':['c'],
'edwaid':['ruby','go'],
'phil':['python','haskell'],
}
for name,languages in favorite_languages.items():
if len(languages) == 1:
print("\n" + name.title() + "'s favorite language is " + languages[0].title())
# 注意只有一个元素在列表中时,要用下标0来获取最后一个元素
else:
print("\n" + name.title() + "'s favorite languages are: ")
for language in languages:
print("\t" + language.title())
结果:
Jen's favorite languages are:
Python
Ruby
Sarah's favorite language is C
Edwaid's favorite languages are:
Ruby
Go
Phil's favorite languages are:
Python
Haskell
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
总结:
1、字典的遍历方法:items()方法:键-值对遍历,返回的值是一个可以迭代序列,list()函数可以将其转为列表
keys()方法:键遍历,返回的值是一个可以迭代序列,list()函数可以将其转为列表
values()方法:值变量,返回值是一个可以迭代序列,list()函数可以将其转为列表
2、嵌套: 在列表中放字典,用于相同属性的对象
在字典中放列表,用于具有相同键的对象
在字典中放置地,用于复制对象
3、在Python对于可迭代的内置数据类型tuple,字符串若放在一个可迭代对象里面,最后一个字符串将以一个个字符变量,因为单个字符串也是可以迭代对象
例子:
tuple_2 = ('你好!')
for ele in list_2:
print(ele)
结果:
你
好
!