A simple dictionary
ailen_0 = {'color':'green','point':5} print(alien_0['color']) print(alien_0['points'])
Dictionary alien_0 stores alien colors and scores
Use dictionary
A dictionary is a series of key value pairs. The values associated with a key can be numbers, strings, lists, or dictionaries
In python, dictionaries are represented by a series of key value pairs enclosed in curly braces ({})
Key value pairs are pairs of two associated values. When a key is specified, the value associated with it is returned, separated by a colon between the key and value, and separated by a comma between key value pairs
Accessing values in the dictionary
Add key value pair
alien_0['x_position'] = 0 alien_0['y_position'] = 0
Add two key value pairs
Modify values in the 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']}.")
Change the value associated with 'color' to 'yellow'
Delete key value pair
Using the del statement, you must specify the dictionary name and the key to delete
alien_0 = {'color': 'green' , 'points':5} del alien_0['points']
A dictionary of similar objects
fav_lan = { 'jan':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } language = fav_lan['sarah'].title() print(f"sarah favorite language is {language}.")
Use get() to access values
An error will be reported when the specified key accessed from the dictionary does not exist
Show traceback
So the method get() is used to return a default value when the specified key does not exist
alien_0 = {'color':'green','speed':'slow'} point_value = alien_0.get('points','no point value assiged.') print(point_value)
Output result: no point value assigned
Traversal dictionary
Traverse all key value pairs
Use for loop
user = { 'username':'efermi', 'first':'enrico', 'last':'femi', } for key,value in user.items(): print(f"\nKey:{key}") print(f"Value:{value}")
Output results
Key:username Value:efermi Key:first Value:enrico Key:last Value:femi
Traverse all values in the dictionary
The method keys() is useful when you do not need to use the values in the dictionary
fav_lan = { 'jan':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } for name in fav_lan.keys(): print(name.title())
The last penultimate line can also be written as
for name in fav_lan:
Output unchanged
Traverse all keys in the dictionary in a specific order
Sort the returned values in the for loop, and use the function sorted() to get a copy of the list of keys in a specific order
fav_lan = { 'jan':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } for name in sorted(fav_lan.keys()): print(f"{name.title()},thank you for taking the poll.")
sorted() uses ASCII code for comparison. If the first character is the same, the next one is compared
Traverse all values in the dictionary
Use the method values() to return a list of values without any keys
fav_lan = { 'jan':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } for language in fav_lan.values(): print(language.title())
To eliminate duplicates, you can use the set. Each element in the set must be unique
fav_lan = { 'jan':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } for language in set(fav_lan.values()): print(language.title())
Simpler usage
languages = {'python','ruby','c','python'} languages {'python','ruby','c'}
nesting
Storing a series of dictionaries in a list or a group of lists as values in a dictionary is called nesting
Dictionary list
Create a list of three alien s
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)
In reality, there are more than three aliens. For example, the following uses range() to generate 30 aliens with the same characteristics
# Create a storage empty list aliens = [] # Create 30 for alien_number in range(30): new_alien = {'color':'green','points':5,'speed':'slow'} aliens.append(new_alien) # Show top five for alien in aliens[:5]: print(alien) # Displays how many have been created print(f"total number of aliens:{len(aliens)}")
Modify some data
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
Store list in dictionary
Sometimes you need to store a list in a dictionary
# Store information about pizza ordered pizza = { 'crust':'thick', 'toppings':['mushrooms','extra cheese'], } # Overview of pizza ordered print(f"you ordered a {pizza['crust']}-crust pizza " "with the following toppings:") for topping in pizza['toppings']: print("\t" + topping)
To print ingredients, write a for loop. To access the list of ingredients, use the key 'toppings'
You can nest a list in the dictionary whenever you need to associate a key to multiple values in the dictionary
fav_lan = { 'jan':['python','ruby'], 'sarah':['c'], 'edward':['ruby','go'], 'phil':['python','haskell'], } for name,languages in fav_lan.items(): print(f"\n{name.title()}'s favorite languages are:") for language in languages: print(f"\t{language.title()}")
Now the value associated with each name is a list. In the main loop of traversing the dictionary, another for loop is used to traverse the list of languages everyone likes
Store dictionary in dictionary
The code can be complicated
users = { 'aeinstein':{ 'first':'albert', 'last':'einstein', 'location':'princetion', }, '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()}")
First, define a user dictionary, which contains two keys' aeinstein 'and' mcurie '
The value associated with each key is a dictionary, then traverse users, and then start accessing the internal dictionary, the variable user_info contains the user information dictionary