Python- Day 18- DICTIONARIES {_}

Nidhi Ashtikar
6 min readOct 21, 2024

--

You’ll learn how to work with Python dictionaries, which allow you to associate pieces of related information through key-value pairs.

You’ll discover how to access and modify dictionary entries, loop through data stored in dictionaries, and nest them inside lists or other dictionaries to model real-world objects effectively.

Dictionaries are collections of key-value pairs, where each key is linked to a value (which can be a number, string, list, or even another dictionary).

Keys and values are separated by colons, and each key-value pair is separated by commas, enclosed within curly braces {}.

Accessing values:

You can retrieve values by referencing the key inside square brackets.

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

>>

green

Adding new key-value pairs:

To add new information to a dictionary, simply define the key with the value like this:

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

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

>>

{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

Modifying values:

Values in a dictionary can be updated by assigning a new value to an existing key:

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']}.")

>>

The alien is green.
The alien is now yellow.

Removing key-value pairs:

Use the del statement to remove a key and its value permanently:

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

>>

{'color': 'green', 'points': 5}
{'color': 'green'}

Empty dictionaries:

You can start with an empty dictionary and fill it later by assigning key-value pairs:

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

>>

{'color': 'green', 'points': 5}

Working with Multiple Objects:

You can also use dictionaries to store similar information about different objects.
For example, a poll of favorite programming languages can be stored like this:

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

language = favorite_languages['sarah'].title()
print(f"Sarah's favorite language is {language}.")

>>

Sarah's favorite language is C.

Accessing Data Safely with get():

Using get() allows you to retrieve a value without encountering an error if the key doesn’t exist.
You can also set a default message if the key isn’t found:

alien_0 = {'color': 'green', 'speed': 'slow'}
print(alien_0['points'])

#This results in a traceback, showing a KeyError:

Traceback (most recent call last):
File "alien_no_points.py", line 2, in <module>
print(alien_0['points'])
~~~~~~~^^^^^^^^^^
KeyError: 'points'

Solution :

alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)

>>

No point value assigned.

Looping Through a Dictionary:

In Python, a dictionary can store small or large amounts of data, from just a few key-value pairs to millions.

Python offers ways to loop through a dictionary to efficiently manage and access the data.

There are several ways to loop through a dictionary, depending on whether you want to work with key-value pairs, keys, or values.

Looping Through All Key-Value Pairs:

A common use of dictionaries is storing related data, such as user information.

user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}

To access and display all of the information in this dictionary, you can use a for loop to iterate through the key-value pairs:

user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}

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

>>

Key: username
Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi

In the above code, the items() method returns each key-value pair, which is then assigned to the variables key and value, respectively.

The loop prints both the key and value for each pair.

You can choose any variable names you want for the key and value. For example:

for k, v in user_0.items():
print(f"\nKey: {k}")
print(f"Value: {v}")

Example: Favorite Programming Languages

Let’s take another dictionary example, where we store the favorite programming languages of several users:

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

for name, language in favorite_languages.items():
print(f"{name.title()}'s favorite language is {language.title()}.")

>>

Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Rust.
Phil's favorite language is Python.

Here, name holds the key (person's name) and language holds the value (favorite language).
Using descriptive variable names helps make the code more readable.

This approach works even if the dictionary contains data for a large number of people.

Looping Through All the Keys in a Dictionary:

You can also loop through only the keys of a dictionary using the keys() method:

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

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

>>

Jen
Sarah
Edward
Phil

Note that using keys() is optional, as looping through a dictionary by default loops through its keys.
So, the code below would produce the same result:

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

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

>>

Jen
Sarah
Edward
Phil

Accessing Values Using Keys:

While looping through keys, you can also access their corresponding values.

For example, let’s send a personalized message to certain friends based on their favorite language:

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

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}!")

>>

Hi Jen.
Hi Sarah.
Sarah, I see you love C!
Hi Edward.
Hi Phil.
Phil, I see you love Python!

In this example, if the current key (name) is in the list friends, a personalized message is printed.

Checking for Specific Keys:

You can use the keys() method to check if a particular key exists in the dictionary.
For example, to see if 'erin' took the poll:

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

if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")

If ‘erin’ isn’t found in the dictionary, a message will be displayed.

Looping Through Dictionary Keys in Order:

Sometimes, you may want to loop through the keys in a specific order.

You can use the sorted() function to sort the keys:

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

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


>>

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.

Looping Through All Values in a Dictionary:

If you are only interested in the values stored in a dictionary, you can use the values() method:

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

print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())

>>

The following languages have been mentioned:
Python
C
Rust
Python

In this example, values() returns all the values in the dictionary, but duplicates may occur. To remove duplicates, you can use a set:

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

for language in set(favorite_languages.values()):
print(language.title())

>>

Python
C
Rust

A set automatically removes duplicates, so this method gives you a list of unique languages mentioned in the poll.

Sets in Python:

You can create a set directly by using braces:

languages = {'python', 'rust', 'c'}
print(languages)

>>

{'python', 'c', 'rust'}

When you see braces with no key-value pairs, you are likely looking at a set. Unlike lists or dictionaries, sets do not maintain any specific order.

If you found this guide helpful then do click on 👏 the button.

Follow for more Learning like this 😊

If there’s a specific topic you’re curious about, feel free to drop a personal note or comment. I’m here to help you explore whatever interests you!

Thanks for spending your valuable time learning to enhance your knowledge!

--

--

Nidhi Ashtikar
Nidhi Ashtikar

Written by Nidhi Ashtikar

Experienced AWS DevOps professional with a passion for writing insightful articles.

No responses yet