Wednesday, 29 July 2020

Dictionaries


    In this chapter you’ll learn how to use Python’s dictionaries, which allow you to connect pieces of related information. You’ll learn how to access the information once it’s in a dictionary and how to modify that information. Additionally, you’ll learn to nest dictionaries inside lists, lists inside dictionaries, and even dictionaries inside other dictionaries.

A Simple Dictionary

Consider a game featuring aliens that can have different colors and point values. The dictionary alien_0 stores the alien’s color and point value. This simple dictionary stores information about a particular alien:

alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color']) gives green
print(alien_0['points']) gives 5

Working with Dictionaries

A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key. A key’s value can be a number, a string, a list, or even another dictionary. In fact, you can use any object that you can create in Python as a value in a dictionary
In Python, a dictionary is wrapped in braces, {}, with a series of keyvalue pairs inside the braces, as shown in the earlier example. A key-value pair is a set of values associated with each other. When you provide a key, Python returns the value associated with that key. Every key is connected to its value by a colon, and individual key-value pairs are separated by commas. You can store as many key-value pairs as you want in a dictionary.

Accessing Values in a Dictionary

To get the value associated with a key, give the name of the dictionary and then place the key inside a set of square brackets, as shown here:

alien_0 = {'color': 'green'} 
print(alien_0['color']) gives green

Adding New Key-Value Pairs

Dictionaries are dynamic structures, and you can add new key-value pairs to a dictionary at any time. For example, to add a new key-value pair, you would give the name of the dictionary followed by the new key in square brackets along with the new value.

alien_0 = {'color': 'green', 'points': 5}  
print(alien_0) gives {'color': 'green', 'points': 5}
alien_0['x_position'] = 0  
alien_0['y_position'] = 25 
print(alien_0) gives gives {'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

Sometimes, you will have to begin with an empty dictionary {} and add new key-value pairs as shown above.

Modifying Values in a Dictionary

To modify a value in a dictionary, give the name of the dictionary with the key in square brackets and then the new value you want associated with that key.

alien_0 = {'color': 'green'}
alien_0['color'] = 'yellow'
print(alien_0) gives {'color': 'yellow'}

Removing Key-Value Pairs

When you no longer need a piece of information that’s stored in a dictionary, you can use the del statement to completely remove a key-value pair. All del needs is the name of the dictionary and the key that you want to remove.

alien_0 = {'color': 'green', 'points': 5}
del alien_0['points']
print(alien_0) gives {'color': 'green'}

A Dictionary of Similar Objects

The previous example involved storing different kinds of information about one object, an alien in a game. You can also use a dictionary to store one kind of information about many objects. For example, say you want to poll a Dictionaries 101 number of people and ask them what their favorite programming language is. A dictionary is useful for storing the results of a simple poll. Here, each key is the name of a person who responded to the poll, and each value is their language choice.

favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }

To use this dictionary, given the name of a person who took the poll, you can easily look up their favorite language:

print("Sarah's favorite language is " + favorite_languages['sarah'].title() + ".") gives Sarah's favorite language is C.

Looping Through a Dictionary

Dictionaries can be used to store information in a variety of ways; therefore, several different ways exist to loop through them. You can loop through all of a dictionary’s key-value pairs, through its keys, or through its values.

Looping Through All Key-Value Pairs

In order to write a for loop for a dictionary, you create names(variables) for the two variables that will hold the key and value in each key-value pair. You can choose any names you want for these two variables.

user_0 = { 'username': 'efermi', 'first': 'enrico', 'last': 'fermi', } 
for key, value in user_0.items(): 
    print("\nKey: " + key) 
    print("Value: " + value) 

Output
Key: last 
Value: fermi 
Key: first 
Value: enrico 
Key: username 
Value: efermi

Looping Through All the Keys in a Dictionary

The keys() method is useful when you don’t need to work with all of the values in a dictionary.

favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
for name in favorite_languages.keys(): 
    print(name.title())

Output
Jen 
Sarah 
Phil 
Edward

Looping Through a Dictionary’s Keys in Order

A dictionary always maintains a clear connection between each key and its associated value, but you never get the items from a dictionary in any predictable order. That’s not a problem, because you’ll usually just want to obtain the correct value associated with each key.
One way to return items in a certain order is to sort the keys as they’re returned in the for loop. You can use the sorted() function to get a copy of the keys in order:

for name in sorted(favorite_languages.keys()): 
    print(name.title() + ", thank you for taking the poll.")

Output
Edward, 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.

This for statement is like other for statements except that we’ve wrapped the sorted() function around the dictionary.keys() method. This tells Python to list all keys in the dictionary and sort that list before looping through it. 

Looping Through All Values in a Dictionary

If you are primarily interested in the values that a dictionary contains, you can use the values() method to return a list of values without any keys. For example, say we simply want a list of all languages chosen in our programming language poll without the name of the person who chose each language:

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())

Output
The following languages have been mentioned: 
Python 
Python 
Ruby

Nesting

Sometimes you’ll want to store a set of dictionaries in a list or a list of items as a value in a dictionary. This is called nesting. You can nest a set of dictionaries inside a list, a list of items inside a dictionary, or even a dictionary inside another dictionary. Nesting is a powerful feature, as the following examples will demonstrate.

A List of Dictionaries

The alien_0 dictionary contains a variety of information about one alien, but it has no room to store information about a second alien, much less a screen full of aliens. How can you manage a fleet of aliens? One way is to make a list of aliens in which each alien is a dictionary of information about that alien. For example, the following code builds a list of three aliens:

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) 

Output
{'color': 'green', 'points': 5} 
{'color': 'yellow', 'points': 10} 
{'color': 'red', 'points': 15}

It’s common to store a number of dictionaries in a list when each dictionary contains many kinds of information about one object. For example, you might create a dictionary for each user on a website and store the individual dictionaries in a list called users. All of the dictionaries in the list should have an identical structure so you can loop through the list and work with each dictionary object in the same way.

A List in a Dictionary

Rather than putting a dictionary inside a list, it’s sometimes useful to put a list inside a dictionary. For example, consider how you might describe a pizza that someone is ordering. If you were to use only a list, all you could really store is a list of the pizza’s toppings. With a dictionary, a list of toppings can be just one aspect of the pizza you’re describing.
In the following example, two kinds of information are stored for each pizza: a type of crust and a list of toppings. The list of toppings is a value associated with the key 'toppings'. To use the items in the list, we give the name of the dictionary and the key 'toppings', as we would any value in the dictionary. Instead of returning a single value, we get a list of toppings:

# Store information about a pizza being ordered. 
pizza = { 'crust': 'thick', 
                'toppings': ['mushrooms', 'extra cheese'], 
             }
# Summarize the order. 
print("You ordered a " + pizza['crust'] + "-crust pizza " + "with the following toppings:") 
for topping in pizza['toppings']: 
    print("\t" + topping)

Output
You ordered a thick-crust pizza with the following toppings: 
mushrooms 
extra cheese

Note: You should not nest lists and dictionaries too deeply. If you’re nesting items much deeper than what you see in the preceding examples or you’re working with someone else’s code with significant levels of nesting, most likely a simpler way to solve the problem exists.

A Dictionary in a Dictionary

You can nest a dictionary inside another dictionary, but your code can get complicated quickly when you do. For example, if you have several users for a website, each with a unique username, you can use the usernames as the keys in a dictionary. You can then store information about each user by using a dictionary as the value associated with their username. In the following listing, we store three pieces of information about each user: their first name, last name, and location. We’ll access this information by looping through the usernames and the dictionary of information associated with each username:

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())

Output
Username: aeinstein 
     Full name: Albert Einstein 
     Location: Princeton 
Username: mcurie 
     Full name: Marie Curie 
     Location: Paris

Notice that the structure of each user’s dictionary is identical. Although not required by Python, this structure makes nested dictionaries easier to work with. If each user’s dictionary had different keys, the code inside the for loop would be more complicated.

Conclusion

In this blog you learned how to define a dictionary and how to work with the information stored in a dictionary. You learned how to access and modify individual elements in a dictionary, and how to loop through all of the information in a dictionary. You learned to loop through a dictionary’s key-value pairs, its keys, and its values. You also learned how to nest multiple dictionaries in a list, nest lists in a dictionary, and nest a dictionary inside a dictionary.

In the next blog you’ll learn about while loops and how to accept input from people who are using your programs. This will be an exciting chapter, because you’ll learn to make all of your programs interactive: they’ll be able to respond to user input.

Post a Comment

Let's make it better!
Comment your thoughts...

Whatsapp Button works on Mobile Device only

Start typing and press Enter to search