I’m YouKoutaku. These codes are from the book python_Crash_Course, 2nd edition. I learned python and took these notes for this book.
6.Dictionary
A datatype that has the key-value.
6.1 sample
1
2
| alien = {'color': 'green', 'points': 5}
|
6.2 using dictionary
6.2.1 check value in dictionary
1
2
3
4
5
6
7
| alien = {'color': 'green', 'points': 5}
print(alien['color'])
print(alien['points'])
new_points = alien['points']
print(f"New points {new_points}")
|
1
2
3
| green
5
New points 5
|
6.2.2 add key in dictionary
1
2
3
4
5
| alien = {'color': 'green', 'points': 5}
alien['xp'] = 0
alien['yp'] = 25
print(alien)
|
1
| {'color': 'green', 'points': 5, 'xp': 0, 'yp': 25}
|
6.2.3 empty dictionary
1
2
| alien = {}
print(alien)
|
6.2.4 change key in dictionary
1
2
3
4
| alien = {'color': 'green', 'points': 5}
alien['color'] = 'yellow'
print(alien)
|
1
| {'color': 'yellow', 'points': 5}
|
6.2.5 deletee key in dictionary
1
2
3
4
5
| alien = {'color': 'green', 'points': 5}
print(alien)
del alien['points']
print(alien)
|
1
2
| {'color': 'green', 'points': 5}
{'color': 'green'}
|
6.2.6 dictionary made by object
1
2
3
4
5
6
7
8
9
10
| favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
language = favorite_languages['sarah'].title()
print(f"Sarah's favorite language is {language}.")
|
1
| Sarah's favorite language is C.
|
6.2.7 using get() to check value
get(key_name, message when the key is't exist)
1
2
3
| # not exist dict
alien_0 = {'color': 'green', 'speed': 'slow'}
print(alien_0['points'])
|
1
2
3
4
5
6
7
8
9
10
11
| ---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Input In [11], in <cell line: 3>()
1 # not exist dict
2 alien_0 = {'color': 'green', 'speed': 'slow'}
----> 3 print(alien_0['points'])
KeyError: 'points'
|
1
2
3
4
5
6
| #To avoid error
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)
|
1
| No point value assigned.
|
1
2
3
4
5
6
7
8
| # E-6-1
p ={
'first_name': "Y",
'last_name': "N",
'age': 18,
'city': "Tokyo"
}
print(p['first_name'],p['last_name'],p['age'],p['city'])
|
6.3 check dictionary by for
6.3.1 key-value
dictionary.item()
1
2
3
4
5
6
7
8
| user_0 = {
'username': 'david',
'first': 'enrico',
'last': 'fermi',
}
for key, value, in user_0.items():
print(f"\neKey:{key}")
print(f"Value:{value}")
|
1
2
3
4
5
6
7
8
| eKey:username
Value:anny
eKey:first
Value:enrico
eKey:last
Value:fermi
|
6.3.key
for a in dictionary = for a in dictionary.keys()
1
2
3
4
5
6
7
8
9
10
11
12
| favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages:
print(name.title())
for name in favorite_languages.keys():
print(name.title())
#same
|
1
2
3
4
5
6
7
8
| Jen
Sarah
Edward
Phil
Jen
Sarah
Edward
Phil
|
1
2
3
4
5
6
7
| # using value by key in for
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(f"Hi {name.title()}.")
if name in friends:
language = favorite_languages[name].title()
print(f"\t{name.title()}, I see you love {language}!")
|
1
2
3
4
5
6
| Hi Jen.
Hi Sarah.
Sarah, I see you love C!
Hi Edward.
Hi Phil.
Phil, I see you love Python!
|
1
2
3
| # not exist
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")
|
1
| Erin, please take our poll!
|
6.3.4 check all of value in dictionary by for
dictionary.values()
1
2
3
4
5
6
7
8
9
10
| 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())
|
1
2
3
4
5
| The following languages have been mentioned:
Python
C
Ruby
Python
|
1
2
3
| # when many values are in dictionary, We need to avoid the same value by using "set()"
for language in set(favorite_languages.values()):
print(language.title())
|
1
2
3
| # create the set that means repeated value
language = {'python', 'ruby', 'c', 'python'}
language
|
1
| {'c', 'python', 'ruby'}
|
6.4 Nesting
create dictionary which have the value as list or create list which have the value as dictionary
6.4.1 create dictionary in list
1
2
3
4
5
6
7
8
| 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)
|
1
2
3
| {'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
|
6.4.2 create list in dictionary
1
2
3
4
5
6
7
8
9
10
11
| 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(topping)
|
1
2
3
| You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
|
6.4.3 create dictionary in dictionary
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| users = {
'einstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'curie': {
'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()}")
|
1
2
3
4
5
6
7
| Username: einstein
Full name: Alberteinstein
Location:Princeton
Username: curie
Full name: Mariecurie
Location:Paris
|