Dictionary In Python

1. DICTIONARY 101

1.1. Defining a Dictionary

A dictionary in Python is a collection of key-value pairs.

  • A dictionary is wrapped in braces, {}

  • Every key is connected to its value by a colon :, and individual key-value pairs are separated by commas ,

  • 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, another dictionary or virtually any object in Python

  • You can store as many key-value pairs as you want in a dictionary

Let’s define a simple dictionary that stores some pieces of information about and store it inside a variable user_car

user_car ={'make': 'honda','model': 'fit','year': 2015}

In the above example, there are three key-value pairs. Keys are make, model and year with their associated values β€” honda, fit and 2015 , respectively.

1.2. 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

print(user_car['make'].title())
print(user_car['model'].title())
Honda
Fit

1.3 Adding New Key-Value Pairs

To add a new key-value pair, you would provide the name of the dictionary followed by the new key in square brackets and assign a value. Let’s add the color and country to our previous dictionary user_car

user_car ={'make': 'honda','model': 'fit','year': 2015}
# dictionary before adding new key-value pairs
print(user_car)

# adding new key-value pairs
user_car['color'] = 'silver'
user_car['country'] = 'japan'

# dictionary after adding new key-value pairs
print(user_car)
{'make': 'honda', 'model': 'fit', 'year': 2015}
{'make': 'honda', 'model': 'fit', 'year': 2015, 'color': 'silver', 'country': 'japan'}

1.4. Starting with an Empty Dictionary

Why we need an empty dictionary? One case would be when storing user-supplied data in a dictionary or when you write code that generates a large number of key-value pairs programatically. Let define an empty dictionary user_car and add few key-value pairs in it:

# defining an empty dictionary
user_car ={}
#printing the same empty dictionary
print(user_car)

# adding new key-value pairs
user_car['make'] = 'honda'
user_car['model'] = 'fit'
user_car['year'] = 2015

# printing dictionary
print(user_car)
{}
{'make': 'honda', 'model': 'fit', 'year': 2015}

1.5. Modifying Values in a Dictionary

To modify a value in a dictionary, the methodology is the same as creating new key-value pair β€” i.e, give the name of the dictionary with the key in square brackets and then the new value you want associated with that key.

# original dictionary
user_car ={'make': 'honda','model': 'fit','year': 2015}
print(f"The car is made in {user_car['year']}")

# modifying year value
user_car['year'] = 2014
print(f"\nWe modified the car year to {user_car['year']}")
The car is made in 2015

We modified the car year to 2014

1.6. Removing Key-Value Pairs

Sometimes, we no longer require a piece of information that’s stored in a dictionary, in such cases, we can use the del statement to permanently remove a key-value pair. All del statement needs is the name of the dictionary and the key that we want to remove.

# defining the dictionary in original form
user_car ={'make': 'honda','model': 'fit','year': 2015}
print(user_car)

# deleting the key-value pair of 'year' key
del user_car['year']

# after removing, printing the dictionary
print(user_car)
{'make': 'honda', 'model': 'fit', 'year': 2015}
{'make': 'honda', 'model': 'fit'}

1.7. A Dictionary of Similar Objects

Up-till now, we are storing different kinds of information about one object, a user car We can also use a dictionary to store one kind of information about many objects as we will do in the following example

# defining dictionary
fav_cars = {
    'tom':'honda',
    'jerry':'toyota',
    'dexter':'tesla',
    'frank':'tesla',
    }

# accessingthe required value from dict
print(f"Dexter loves to drive {fav_cars['dexter'].title()}")
Dexter loves to drive Tesla

In the above example, we wrote a multi-line dictionary, in which each key-value pair is written in new line. The comma at the end of last value is not needed but a good practice.

2. LOOPING THROUGH A DICTIONARY

Several different ways exist to loop through a dictionary:

2.1. Looping Through all Key-Value Pairs

a. Example 1:

In the following example, we will print all the key-value pairs in the dictionary:

# defining dict
user_car ={'make': 'honda','model': 'fit','year': 2015}

# looping through dict
for key, value in user_car.items():
    print(f"\nKey: {key}")
    print(f"Value: {value}")
    
print("\nAll key-value pairs are printed")
Key: make
Value: honda

Key: model
Value: fit

Key: year
Value: 2015

All key-value pairs are printed

The for loop was defined in the following line:

for key, value in user_car.items():

the user_car.items(): part of the code read the entire key-value pairs.

However, you can use any keyword for the key and value, for example:

for k, v in user_car.items():

b. Example 2:

Let’s loop through a dictionary that stores one kind of information for several objects:

# defining dict
fav_cars = {
    'tom':'honda',
    'jerry':'toyota',
    'dexter':'tesla',
    'frank':'tesla',
    }

# looping through dict
for name, car in fav_cars.items():
    print(f"{name.title()} favorite car is {car.title()}")
Tom favorite car is Honda
Jerry favorite car is Toyota
Dexter favorite car is Tesla
Frank favorite car is Tesla

2.2. Looping Through all the Keys

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

# defining dict
fav_cars = {
    'tom':'honda',
    'jerry':'toyota',
    'dexter':'tesla',
    'frank':'tesla',
    }

# looping and printing 'keys' only
print("Dictionary keys:")
for name in fav_cars.keys():
    print (f"\t{name.title()}")
Dictionary keys:
	Tom
	Jerry
	Dexter
	Frank

The for loop was defined in the following line :

for name in fav_cars.keys():

whereas the fav_cars.keys(): part of the code only read key

However, we can use the following shortcut:

for name in fav_cars:

a. Looping with if statement

In this example, we will print custom message if the key value is Dexter:

# defining dict
fav_cars = {
    'tom':'honda',
    'jerry':'toyota',
    'dexter':'tesla',
    'frank':'tesla',
    }

# looping with if statement
for name in fav_cars.keys():
    if name == 'dexter':
        print(f"Hello {name.title()}, please go to room 007")
    else:
        print(f"Hello {name.title()}, please go to room B101")
Hello Tom, please go to room B101
Hello Jerry, please go to room B101
Hello Dexter, please go to room 007
Hello Frank, please go to room B101

b. Looping through keys in order

For example, we want to print the key names in alphabetic order. To do this, we will use sorted function

# defining dict
fav_cars = {
    'tom':'honda',
    'jerry':'toyota',
    'dexter':'tesla',
    'frank':'tesla',
    }

# printing keys in order
print("Keys in the dictionary are:")
for name in sorted(fav_cars.keys()):
    print(f"\t{name.title()}")
Keys in the dictionary are:
	Dexter
	Frank
	Jerry
	Tom

2.3. Looping Through All Values

We can use the .values() method to return a list of values without any keys. For example, we would like to print the favorite cars without any associated key:

# defining dict
fav_cars = {
    'tom':'honda',
    'jerry':'toyota',
    'dexter':'tesla',
    'frank':'tesla',
    }

# printing values of dict
print("Favorite cars are:")
for car in fav_cars.values():
    print(f"\t{car.title()}")
Favorite cars are:
	Honda
	Toyota
	Tesla
	Tesla

a. Looping through values without repetition

In above example, β€˜Tesla’ is printed twice. However, we are only interested in the unique values of car names. For this purpose, we can use the set() function

# defining dict
fav_cars = {
    'tom':'honda',
    'jerry':'toyota',
    'dexter':'tesla',
    'frank':'tesla',
    }

# printing only the unique values of dict
print("Favorite cars in the list are:")
for car in set(fav_cars.values()):
    print(f"\t{car.title()}")
Favorite cars in the list are:
	Tesla
	Honda
	Toyota

ALERT: If you have noticed that the order of printed values are not in the same order as contained in the original dictionary, this is how the Python work this out internally.

3. NESTING

Sometimes you want to store:

  • a set of dictionaries inside a list, or

  • a list of items as a value in a dictionary, or

  • a dictionary inside another dictionary … this is called Nesting

3.1. A List of Dictionaries

In the following example, we store two dictionaries inside a list:

# defining first dict
car_1 = {'make': 'honda','model': 'fit','year': 2015}
# defining second dict
car_2 = {'make': 'tesla', 'model': '3', 'year': 2018}

# storing dictionaries inside list
cars = [car_1, car_2]

# looping through list
for car in cars:
    print(car)
{'make': 'honda', 'model': 'fit', 'year': 2015}
{'make': 'tesla', 'model': '3', 'year': 2018}

3.2. A List in a Dictionary

We can also nest a list inside a dictionary. Let’s suppose we are storing information about blog post in a dictionary and within this dictionary, we will store the tags related to this blog post inside a list:

# defining dict
blog_post ={
    'title':'This is title',
    'description':'This is description',
    'tags':['tag1', 'tag2', 'tag3']
    } 

# running for loop to retrieve
# list of tags associated with key 'tags' 
for tag in blog_post['tags']:
    print(tag)
tag1
tag2
tag3

a. One object, multiple information

In earlier example, we stored a single value of car for each person. However, we can use a list to store more than one cars for each person:

# defining dict with 'values' as list
fav_cars = {
    'tom':['honda'],
    'jerry':['toyota', 'bmw'],
    'dexter':['tesla', 'byd'],
    'frank':['tesla','buick'],
    }

# running primary 'for' loop for dict key-values
for name, cars in fav_cars.items():
    print(f"\n{name.title()}'s favorite cars are:")
    # running another 'for' loop for list
    for car in cars:
        print(f"\t{car.title()}")
Tom's favorite cars are:
	Honda

Jerry's favorite cars are:
	Toyota
	Bmw

Dexter's favorite cars are:
	Tesla
	Byd

Frank's favorite cars are:
	Tesla
	Buick

b. Refining the code

We can see in the above example that even for person with single favorite cars, we are printing the word β€œβ€¦ cars are:” , instead of β€œβ€¦ car is:” Let refine the code using if statement to handle this situation:

# defining dict with 'values' as list
fav_cars = {
    'tom':['honda'],
    'jerry':['toyota', 'bmw'],
    'dexter':['tesla', 'byd'],
    'frank':['tesla','buick'],
    }

# running primary 'for' loop for dict key-values
for name, cars in fav_cars.items():
    # checking if the number of cars is equal to 1
    if len(cars) == 1:
        print(f"{name.title()}'s favorite car is:")
    else:
        print(f"{name.title()}'s favorite cars are:")
    for car in cars:
        print(f"\t{car.title()}")
Tom's favorite car is:
	Honda
Jerry's favorite cars are:
	Toyota
	Bmw
Dexter's favorite cars are:
	Tesla
	Byd
Frank's favorite cars are:
	Tesla
	Buick

3.3. A Dictionary in a Dictionary

Suppose our dictionary stores user information, where the key is the username and value is another dictionary including the related information about the user:

# defining dict with 'values' as another dictionary
users = {
    'tommy': {
        'first':'tom',
        'last':'cruise',
        'location':'new york',
    },
    'dex':{
        'first':'dexter',
        'last':'morgan',
        'location':'florida',
    },
}

# running for loop inside dict
for name, user_info in users.items():
    full_name = f"{user_info['first'].title()} {user_info['last'].title()}"
    location = f"{user_info['location'].title()}"
    
    print(f"\nUsername: {name}")
    print(f"Full name: {full_name}")
    print(f"Location: {location}")
Username: tommy
Full name: Tom Cruise
Location: New York

Username: dex
Full name: Dexter Morgan
Location: Florida

ALERT: Please note that the structure of each user dictionary is identical. However, we can make it different but the code will be more complicated.

Last updated