Code:[ZachxPKU/Python Crash Course]
Chapter 6 Dictionaries
6.1 A simple Dictionary
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
print(alien_0['color'])
print(alien_0['points'])
6.2 Working with dictionaries
alien_0 = {'color': 'green'}
6.2.1 Accessing values in dictionary
alien_0 = {'color': 'green'}
print(alien_0['color'])
alien_0 = {'color': 'green', 'points': 5}
new_points = alien_0['points']
print(f'You just earned {new_points} points!')
```python
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
6.2.3 Starting with an empty dictionary
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
6.2.4 Modifying values in a dictionary
alien_0 = {'color': 'green'}
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}.")
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original x-position: {alien_0['x_position']}")
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"New position: {alien_0['x_position']}")
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
alien_0['speed'] = 'fast'
print(f"Original x-position: {alien_0['x_position']}")
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"New position: {alien_0['x_position']}")
6.2.5 Removing key-value pairs
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
6.2.6 A dicitonary of similar objects
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
language = favorite_languages['sarah'].title()
print(f"Sarah's favorite language is {language}")
需要注意:字典最后一个键值对会面一般会有一个“,”,这样在以后修改字典时,不易发生忘记逗号的错误。但其实,有没有逗号都是可以的。
6.2.7 Using get() to access values
alien_0 = {'color': 'green', 'speed': 'slow'}
print(alien_0['points'])
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)
TRY IT YOURSELF
- person.py
- favorite_numbers.py
- glossary.py
6.3 Looping through a dictionary
6.3.1 Looping throught all key-value pairs
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print(f'\nKey:{key}')
print(f'Value:{value}')
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(f"{name.title()}'s favorite language is {language.title()}.")
6.3.2 Looping through all keys in a dictionary
for name in favorite_languages.keys():
print(name.title())
for name in favorite_languages:
print(name.title())
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
language = favorite_languages[name].title()
print(f"\t{name.title()}, I see you love {language}!")
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")
6.3.3 Looping through a dictionary’s keys in a particular order
for name in sorted(favorite_languages.keys()):
print(f"{name.title()}, thank you for taking the poll.")
6.3.4 Looping through all values in a dictionary
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
TRY IT YOURSELF
- glossary_2.py
- rivers.py
- polling.py
6.4 Nesting
6.4.1 A list of dictionaries
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)
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("...")
print(f"Total number of aliens: {len(aliens)}")
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("...")
6.4.2 A list in a dictionaries
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
print(f"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(f"\n{name.title()}'s favorite languages are:")
for language in languages:
print(f"\t{language.title()}")
6.4.3 A dictionary in a dictionary
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print(f"\nUsername: {username}")
full_name = f"{user_info['first']} {user_info['last']}"
location = user_info['location']
print(f"\tFull name: {full_name.title()}")
print(f"\tLocation: {location.title()}")
TRY IT YOURSELF
- people.py
- pets.py
- favorite_places.py
- favorite_numbers_2.py
- cities.py
6.5 Summary
|