Python Dictionary: A Beginner’s Guide

If you’re new to programming or just starting your journey with Python, understanding the Python dictionary is essential. Dictionaries are powerful data structures that can be used to store all sorts of data. In this blog post, we’ll take a look at what dictionaries are, why they’re useful, and how to work with them in Python.

What is Python Dictionary?

A Python dictionary is like a real-life dictionary, but instead of words and definitions, it stores pairs of information called key-value pairs. Each key is a unique identifier, like a word, and the corresponding value is the data associated with that key, like a definition.

For example, let’s say you have a dictionary to store the names and ages of your friends. Each friend’s name is key, and their age is the corresponding value. So, when you want to know the age of a specific friend, you can use their name as the key to retrieve their age from the dictionary.

Why Use Python Dictionary?

Dictionaries in Python are super versatile and have a bunch of awesome advantages. One cool thing about dictionaries is their speedy lookup feature. You can quickly find values by using special keys instead of searching through all the data. It’s like finding exactly what you need in a flash.

Another fantastic feature is that dictionaries can be changed whenever you want. You can add, update, or remove key-value pairs as needed. It’s like having a customizable tool that adapts to your specific requirements.

Dictionaries are also great for organizing data. You can think of them as neat containers that hold related information together.

What’s even more exciting is that dictionaries allow you to make connections between different pieces of information. By linking keys and values, you can explore relationships and analyze connections.

Last but not least, dictionaries are very useful for manipulating data efficiently. Whether you need to count, group or do perform calculations, dictionaries have your back. They make handling data feel like magic!

Creating a Python Dictionary

Start by using curly braces { } to indicate that you’re creating a dictionary.

Inside the curly braces, you’ll specify key-value pairs. Each key-value pair is separated by a colon “:” The key represents the identifier, while the value is the given data.

For example:

my_dictionary = {"key1": value1, "key2": value2, "key3": value3}

you can eplace key1, key2, and key3 with your own keys, and value1, value2, and value3 with the corresponding values.

Let’s see an example. I am here creating a dictionary of my friends and their ages.

aman_friends = {"Pankaj": 25, "Tejas": 28, "Monu": 24}

print(aman_friends)

Output:

{'Pankaj': 25, 'Tejas': 28, 'Monu': 24}

Accessing Python Dictionaries

Accessing values in dictionaries is super easy! Let’s see how you can retrieve specific values using their corresponding keys:

Start with the dictionary you created or have available. For example, let’s use the person_info dictionary we created earlier:

1. Accessing Values by Key

You can access a specific value in the dictionary by using its corresponding key inside square brackets []. Here’s an example:

print(aman_friends["Pankaj"])

Output:

25

In this case, “Pankaj” is the key, and 25 is the associated value. By accessing aman_friends[“Pankaj”], you retrieve the value 25 from the dictionary.

2. Checking if a Key Exists

Before accessing a value, it’s often useful to check if a key exists in the dictionary. You can use the in keyword to check for key existence. Here’s an example:

aman_friends = {"Pankaj": 25, "Tejas": 28, "Monu": 24}


if "Tejas" in aman_friends:
    print("Tejas is a friend!")

Output:

Tejas is a friend!

In this case, the if statement checks if the key “Tejas” exists in the aman_friends dictionary. Since it does exist, the corresponding message is printed.

3. Using the get() Method

Another way to access dictionary values is by using the get() method. It allows you to retrieve the value associated with a key. If the key doesn’t exist, it returns a default value (or None if not specified). Here’s an example:

age = aman_friends.get("Monu")
print(age)

Output:

24

In this case, aman_friends.get(“Monu”) retrieves the value associated with the key “Monu”, which is 24. The value is then assigned to the variable age and printed.

Python Dictionary Methods and Operations

Method/OperationDescription
keys()Returns a view object containing the keys of the dictionary.
values()Returns a view object containing the values of the dictionary.
items()Returns a view object containing tuples of key-value pairs in the dictionary.
get(key)Returns the value associated with the specified key. If the key doesn’t exist, it returns a default value (or None if not specified).
pop(key)Removes and returns the value associated with the specified key.
popitem()Removes and returns the last key-value pair inserted into the dictionary.
update(dict2)Updates the dictionary with the key-value pairs from another dictionary dict2.
clear()Removes all key-value pairs from the dictionary, making it empty.
len()Returns the number of key-value pairs in the dictionary.
inChecks if a key exists in the dictionary. Returns True if the key is present and False otherwise.
copy()Returns a shallow copy of the dictionary.
setdefault(key)Returns the value associated with the specified key. If the key doesn’t exist, it inserts the key with a default value (or None if not specified).
dict.fromkeys()Creates a new dictionary with the specified keys and a default value.
dict.setdefault()Inserts a key-value pair into the dictionary if the key doesn’t already exist.
dict.update()Updates the dictionary with key-value pairs from another dictionary or iterable.
delDeletes a key-value pair from the dictionary using the del statement.
dict.clear()Removes all key-value pairs from the dictionary, making it empty.
dict.items()Returns a list of tuples containing key-value pairs in the dictionary.
dict.keys()Returns a list of keys in the dictionary.
dict.values()Returns a list of values in the dictionary.
dict.popitem()Removes and returns a random key-value pair from the dictionary.

Here I will explain to you the most important one.

keys() Method

The keys() method returns a view object that contains all the keys in a dictionary. You can convert this view object to a list or iterate over it to access the keys individually.

Example 1 :

aman_friends = {"Pankaj": 25, "Tejas": 28, "Monu": 24}
keys = aman_friends.keys()
print(keys)

Output:

dict_keys(['Pankaj', 'Tejas', 'Monu'])

In this example, aman_friends.keys() returns a view object containing the keys of the aman_friends dictionary. By printing keys, you see the output as dict_keys([‘Pankaj’, ‘Tejas’, ‘Monu’]).

Example 2:

aman_friends = {"Pankaj": 25, "Tejas": 28, "Monu": 24}
for key in aman_friends:
    print(key)

Output:

Pankaj
Tejas
Monu

values() Method

The values() method returns a view object that contains all the values in a dictionary. Similar to keys(), you can convert this view object to a list or iterate over it to access the values individually.

Example 1 :

aman_friends = {"Pankaj": 25, "Tejas": 28, "Monu": 24}
values = aman_friends.values()
print(values)

Output:

dict_values([25, 28, 24])

In this example, aman_friends.values() returns a view object containing the values of the aman_friends dictionary. By printing values, you see the output as dict_values([25, 28, 24]).

Example 2 :

aman_friends = {"Pankaj": 25, "Tejas": 28, "Monu": 24}
for value in aman_friends.values():
    print(value)

Output:

25
28
24

or we can use both :

aman_friends = {"Pankaj": 25, "Tejas": 28, "Monu": 24}
for key, value in aman_friends.items():
    print(key, value)

Output:

Pankaj 25
Tejas 28
Monu 24

items() Method

The items() method returns a view object that contains tuples of key-value pairs in a dictionary. This allows you to iterate over the key-value pairs or convert them into a list. Here’s an example:

aman_friends = {"Pankaj": 25, "Tejas": 28, "Monu": 24}
items = aman_friends.items()
print(items)

Output:

dict_items([('Pankaj', 25), ('Tejas', 28), ('Monu', 24)])

In this example, aman_friends.items() returns a view object containing tuples of key-value pairs from the aman_friends dictionary. By printing items, you see the output as dict_items([(‘Pankaj’, 25), (‘Tejas’, 28), (‘Monu’, 24)]).

Checking if a Key Exists

To check if a key exists in a dictionary, you can use the in keyword. It returns True if the key is present and False otherwise.

Here’s an example:

def check_friend(dictionary, name):
    if name in dictionary:
        return f"{name} is a friend!"
    else:
        return f"{name} is not a friend."

aman_friends = {"Pankaj": 25, "Tejas": 28, "Monu": 24}
print(check_friend(aman_friends, "Pankaj"))
print(check_friend(aman_friends, "John"))

Output:

Pankaj is a friend!
John is not a friend.

Dictionary Comprehensions in Python

In Python, you can use dictionary comprehensions to create dictionaries in a concise and readable manner. A dictionary comprehension allows you to create a dictionary by specifying the key-value pairs and any necessary conditions in a single line of code.

new_dict = {key_expression: value_expression for item in iterable if condition}

Example:

numbers = [1, 2, 3, 4, 5]

# Create a dictionary where the keys are the numbers and values are their squares
squared_dict = {num: num**2 for num in numbers}

print(squared_dict)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

In this example, we use dictionary comprehension to create a new dictionary squared_dict where the keys are the numbers from the numbers list, and the values are the squares of those numbers. The comprehension iterates over each number in the numbers list and assigns the key-value pairs accordingly.

Example of Python Dictionary

Let’s say you are building a student management system, and you want to store information about students. You can use a dictionary to represent each student, where the student’s unique ID serves as the key and the student’s details (name, age, grade, etc.) are stored as values.

students = {
    "Tejas": {"age": 28, "grade": 12, "address": "Mumbai, India"},
    "Pankaj": {"age": 25, "grade": 10, "address": "Delhi, India"},
    "Monu": {"age": 24, "grade": 11, "address": "Bangalore, India"}
}

In this example, the dictionary students represent a student management system with three students: Tejas, Pankaj, and Monu. Each student’s details are stored as a dictionary value, where “age” represents the student’s age, “grade” represents the student’s grade level, and “address” represents the student’s address in India.

You can access and print the information of each student using their names as keys:

for name, details in students.items():
    print(f"Name: {name}")
    print(f"Age: {details['age']}")
    print(f"Grade: {details['grade']}")
    print(f"Address: {details['address']}")
    print()

Output:

Name: Tejas
Age: 28
Grade: 12
Address: Mumbai, India

Name: Pankaj
Age: 25
Grade: 10
Address: Delhi, India

Name: Monu
Age: 24
Grade: 11
Address: Bangalore, India

Leave a Comment