popolo - code simple..

popolo - code simple..

Python Basics - Dictionaries

Python Basics - Dictionaries

Theodoros Kafantaris's photo
Theodoros Kafantaris
·May 3, 2022·

6 min read

Table of contents

In this series we’ll learn how to use Python’s dictionaries, which allow us to connect pieces of related information. Python provides us another composite data type called a dictionary, which is similar to a list in that it is a collection of objects. Dictionaries and lists share the following characteristics:

  • Both are mutable.
  • Both are dynamic. They can grow and shrink as needed.
  • Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.

Dictionaries differ from lists primarily in how elements are accessed:

  • List elements are accessed by their position in the list, via indexing.
  • Dictionary elements are accessed via keys.

A Simple Dictionary

Consider a car that can have different brands and colors. This simple dictionary stores information about a particular car:

first_car = {'brand': 'Honda', 'color': 'grey'}

print(first_car['brand'])
# 'Honda'
print(first_car['color'])
# 'grey'

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 key-value pairs inside the braces, as shown in the earlier example:

first_car = {'brand': 'Honda', 'color': 'grey'}

A key-value pair is a set of values associated with each other. When we 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. We can store as many key-value pairs as you want 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:

first_car = {'brand': 'Honda', 'color': 'grey'}

print(first_car['brand'])
# 'Honda'

Adding New Key-Value Pairs

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

Let’s add one new piece of information to the first_car dictionary:

first_car['model'] = 'Civic'

print(first_car)
# {'brand': 'Honda', 'color': 'grey', 'model': 'Civic'}

Starting with an Empty Dictionary

It’s sometimes convenient, or even necessary, to start with an empty dictionary and then add each new item to it. To start filling an empty dictionary, define a dictionary with an empty set of braces and then add each key-value pair on its own line. For example, here’s how to build the first_car dictionary using this approach:

first_car = {}
first_car['brand'] = 'Honda'
first_car['color'] = 'grey'
print(first_car)

# {'brand': 'Honda', 'color': 'grey'}

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 we want associated with that key.

first_car['color'] = 'yellow'
print(f"The car is now {first_car['color']}.")

Removing Key-Value Pairs

When we no longer need a piece of information that’s stored in a dictionary, we 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.

first_car = {'brand': 'Honda', 'color': 'grey'}
print(first_car)
# {'brand': 'Honda', 'color': 'grey'}

del first_car['color']
print(first_car)
{'brand': 'Honda'}

Using get() to Access Values

Using keys in square brackets to retrieve the value we’re interested in from a dictionary might cause one potential problem: if the key we ask for doesn’t exist, we'll get an error.

For dictionaries, specifically, you can use the get() method to set a default value that will be returned if the requested key doesn’t exist.

The get() method requires a key as a first argument. As a second optional argument, we can pass the value to be returned if the key doesn’t exist:

first_car = {'brand': 'Honda', 'color': 'grey'}
model= first_car.get('model','No model assigned')
print(model)
# No model assigned

Looping Through a Dictionary

A single Python dictionary can contain just a few key-value pairs or millions of pairs. Because a dictionary can contain large amounts of data, Python lets us loop through a dictionary. Dictionaries can be used to store information in a variety of ways; therefore, several different ways exist to loop through them. We can loop through all of a dictionary’s key-value pairs, through its keys, or through its values.

Looping Through All Key-Value Pairs

user = {
    'username': 'thkafadaris',
    'first': 'Theodoros',
    'last': 'Kafantaris',
    }

for key, value in user.items():
    print(f"\nKey: {key}")
    print(f"Value: {value}")

In the following example we can use different name for variables in loop.

favorite_food={
   'tom': 'omelete',
   'sarah' : 'beef',
   'jason' : 'spaghetti'
}
for name, food in favorite_food.items():
    print(f"{name.title()}'s favorite food is {food.title()}.")

Looping Through All the Keys in a Dictionary

The keys() method is useful when we don’t need to work with all of the values in a dictionary. Let’s loop through the favorite_food dictionary and print the names of everyone who took the poll:

for name in favorite_food.keys():
       print(name.title())

Looping through the keys is actually the default behavior when looping through a dictionary, so this code would have exactly the same output if you wrote . . .

for name in favorite_food:
       print(name.title())

Looping Through All Values in a Dictionary

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

for food in favorite_food.values():
    print(food.title())

Nesting

Sometimes we'll want to store multiple dictionaries in a list, or a list of items as a value in a dictionary. This is called nesting. We can nest 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 first_car dictionary contains a variety of information about one car, but it has no room to store information about a second car. How can you manage a group of cars? One way is to make a list of cars in which each car is a dictionary of information about that car. For example, the following code builds a list of three cars:

car1 = {'brand': 'Honda', 'color': 'grey'}
car2 = {'brand': 'Toyota', 'color': 'red'}
car3 = {'brand': 'Nissan', 'color': 'green'}

cars= [car1,car2,car3]

for car in cars:
    print(car)

If we want to add a new car in the existing cars we can use the append() method.

car1 = {'brand': 'Honda', 'color': 'grey'}
car2 = {'brand': 'Toyota', 'color': 'red'}
car3 = {'brand': 'Nissan', 'color': 'green'}

cars= [car1,car2,car3]

new_car= {'brand': 'Renault', 'color': 'orange'}
cars.append(new_car)
print(cars)

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 car that someone is ordering. If we were to use only a list, all you could really store is a list of the car’s extras. With a dictionary, a list of extras can be just one aspect of the car we’re describing.

 # Store information about a car being ordered.
car = {
       'model': 'Civic',
       'extras': ['A/C', 'ABS'],
       }
# Summarize the order.
print(f"You ordered a {car['model']} "
       "with the following extras:")
for extra in car['extras']:
      print(f"\t{extra}")
#You ordered a Civic with the following extras:
# A/C
# ABS
 
Share this