Dictionaries: Mapping Key-Value Pairs

A dictionary in Python is a way to store data in key-value pairs. Think of it as a real-life dictionary where you look up a word (the key) to find its definition (the value). Each key in a Python dictionary is unique, and it is associated with a specific value.

Key Features of Dictionaries :

  • Unordered: The items in a dictionary don’t have a specific order.
  • Changeable: You can add, remove, or change items in a dictionary.
  • Indexed: You can use keys to access specific values.
  • Unique Keys: Each key in a dictionary must be unique.

How to Create Dictionaries

You can create a dictionary by placing a comma-separated list of key-value pairs inside curly braces {}. Each key is followed by a colon :, and then the value.

Syntax:

dictionary_name = {

    key1: value1,

    key2: value2,

    ...

}

Let’s go through some examples to illustrate the process of creating dictionaries:

Example 1: Creating a dictionary representing a person’s information

In this example, we’ll create a dictionary called person. This dictionary will have three key-value pairs. The keys are 'name', 'age', and 'city', and the corresponding values for these keys will be 'Jack', 25, and 'New York'.

person = {

    'name': 'Jack',

    'age': 25,

    'city': 'New York'

}

Example 2: Creating a dictionary with different data types

Now, we will create a dictionary called data that has different types of values. It includes a string ('name'), an integer ('age'), a boolean ('is_student'), a list ('grades'), and another dictionary inside it ('address').

data = {

    'name': 'Jane',

    'age': 18,

    'is_student': True,

    'grades': [80, 85, 90],

    'address': {

        'street': '123 Main St',

        'city': 'San Francisco'

    }

}

Create an Empty Dictionary

You can also start with an empty dictionary and add key-value pairs to it as needed. This is useful when you want to create a dictionary dynamically based on certain conditions or inputs.

To create an empty dictionary, you simply use a pair of curly braces {} or the dict() function.

After that, you can add key-value pairs to an empty dictionary by using the assignment operator = with the dictionary’s key in square brackets []. If the key already exists in the dictionary, the value will be updated. If the key doesn’t exist, a new key-value pair will be added.

Example 1:

person = {}

person['name'] = 'Kate'

person['age'] = 28

person['city'] = 'London'

Example 2: Updating Dictionary Values

person = {'name': 'Aryan', 'age': 28, 'city': 'New York'}

person['age'] = 26
person['city'] = 'San Francisco'

print(person) 

Output:

{'name': 'Aryan', 'age': 26, 'city': 'San Francisco'}

Example 3: Adding New Key-Value Pairs

person = {'name': 'Aryan', 'age': 28, 'city': 'San Francisco'}

person['occupation'] = 'Software Engineer'

print(person)  

Output:

{'name': 'Aryan', 'age': 28, 'city': 'San Francisco', 'occupation': 'Software Engineer'}

Accessing Dictionary Values

In a Python dictionary, you use keys to access their associated values. Each key in a dictionary is unique and serves as an index for the value it stores.

Example:

person = {'name': 'John', 'age': 25, 'city': 'New York'}

print(person['name'])
print(person['age'])

Output:

John
25

Handling Non-Existent Keys

When you try to access a key that doesn’t exist in the dictionary, Python raises a KeyError. This error indicates that the key you are trying to access is not present in the dictionary.

To avoid KeyError, you can use the get() method. This method returns the value for the given key if it exists, otherwise, it returns None or a specified default value.

Example:

student_info = {
    "name": "Shirley",
    "age": 18,
    "major": "Computer Science"
}

# Using get() method to access values
name = student_info.get("name")
height = student_info.get("height", "Not Specified")

print("Name:", name)       
print("Height:", height)

Output:

Name: Shirley
Height: Not Specified

Using in Operator

Another way to handle non-existent keys is to check if the key is in the dictionary using the in operator. This operator returns True if the key is present in the dictionary and False otherwise.

Example:

person = {'name': 'Aryan', 'age': 26, 'city': 'San Francisco'}

if 'age' in person:
    print("Age:", person['age'])
else:
    print("Age not found")

Output:

Age: 26

Removing Key-Value Pairs

Dictionaries are flexible and allow you to remove key-value pairs when they are no longer needed. There are several ways to do this, each with its use case. Let’s explore them.

Using the del Statement

The del statement removes a key-value pair from the dictionary based on the key. If the key does not exist, it raises a KeyError.

Example:

person = {'name': 'Aryan', 'age': 26, 'city': 'San Francisco'}

del person['age']
print(person)

Output:

{'name': 'Aryan', 'city': 'San Francisco'}

Using the pop() Method

The pop() method removes a key-value pair based on the key and returns the value. If the key does not exist, it raises a KeyError. You can also provide a default value to avoid the error if the key is not found.

Example:

student_info = {
    "name": "Shirley",
    "age": 18,
    "major": "Computer Science"
}

# Removing an entry using pop and getting the value
age = student_info.pop("age")
print(student_info)
print("Removed age:", age)

# Trying to pop a non-existent key with a default value
height = student_info.pop("height", "Not Specified")
print("Height:", height)

Output:

{'name': 'Shirley', 'major': 'Computer Science'}
Removed age: 18
Height: Not Specified

Using popitem()

The popitem() method removes and returns the last key-value pair from the dictionary as a tuple. If the dictionary is empty, it raises a KeyError.

Example:

car = {
    "brand": "Toyota",
    "model": "Corolla",
    "year": 2020
}

# Removing the last entry using popitem
last_item = car.popitem()
print(car)
print("Removed item:", last_item)

Output:

{'brand': 'Toyota', 'model': 'Corolla'}
Removed item: ('year', 2020)

Clearing All Entries of a Dictionary

The clear() method removes all key-value pairs from the dictionary, leaving it empty.

Example:

person = {'name': 'Aryan', 'age': 26, 'city': 'San Francisco'}

person.clear()
print(person)

Output:

{}

Dictionary Comprehensions

Dictionary comprehensions in Python provide a concise way to create dictionaries. Just like list comprehensions, dictionary comprehensions allow you to generate dictionaries in a single line of code, which makes the code more readable and efficient.

The basic syntax for dictionary comprehension is:

{key_expression: value_expression for item in iterable}

Example 1: Simple Dictionary Comprehension

Suppose we want to create a dictionary where the keys are numbers from 1 to 5 and the values are their squares.

squares = {x: x**2 for x in range(1, 6)}
print(squares)

Output:

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

Example 2: Conditional Dictionary Comprehension

You can also add conditions to a dictionary comprehension to include only certain items.

even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares)

Output:

{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

Example 3: Transforming Data

Dictionary comprehensions can be useful for transforming data. For instance, converting a list of tuples into a dictionary:

pairs = [("apple", 2), ("banana", 3), ("cherry", 5)]
fruit_dict = {fruit: quantity for fruit, quantity in pairs}
print(fruit_dict) 

Output:

{'apple': 2, 'banana': 3, 'cherry': 5}

Example 4: Filtering Data

You can also add conditions to a dictionary comprehension to include only certain items.

grades = {"Shreya": 85, "Max": 78, "Steve": 92, "Monica": 60}
passed_students = {student: grade for student, grade in grades.items() if grade >= 70}
print(passed_students)

Output:

{'Shreya': 85, 'Max': 78, 'Steve': 92}

Nested Dictionaries

A nested dictionary is a dictionary within a dictionary. This allows you to store more complex data structures in a hierarchical manner.

Here’s an example of how to create a nested dictionary:

students = {
    "Amit": {"age": 21, "major": "Computer Science"},
    "Bala": {"age": 22, "major": "Mathematics"},
    "Chitra": {"age": 20, "major": "Physics"}
}

In this example, students is a dictionary where each key is a student’s name, and each value is another dictionary containing details about that student.

Accessing Nested Dictionary Values

To access values in a nested dictionary, you use multiple square brackets:

Example:

students = {
    "Amit": {"age": 21, "major": "Computer Science"},
    "Bala": {"age": 22, "major": "Mathematics"},
    "Chitra": {"age": 20, "major": "Physics"}
}

# Accessing Amit's age
amit_age = students["Amit"]["age"]
print(amit_age)

# Accessing Bala's major
bala_major = students["Bala"]["major"]
print(bala_major)

Output:

21
Mathematics

Adding New Entries

You can add a new entry to a nested dictionary by specifying the key path:

Example:

students = {
    "Amit": {"age": 21, "major": "Computer Science"},
    "Bala": {"age": 22, "major": "Mathematics"},
    "Chitra": {"age": 20, "major": "Physics"}
}

# Adding a new student
students["Deepak"] = {"age": 23, "major": "Chemistry"}
print(students["Deepak"])

Output:

{'age': 23, 'major': 'Chemistry'}

Updating Existing Entries

To update an existing entry in a nested dictionary, you specify the key path and assign a new value:

Example:

students = {
    "Amit": {"age": 21, "major": "Computer Science"},
    "Bala": {"age": 22, "major": "Mathematics"},
    "Chitra": {"age": 20, "major": "Physics"}
}

# Updating Chitra's age
students["Chitra"]["age"] = 25
print(students["Chitra"])

Output:

{'age': 25, 'major': 'Physics'}

Removing Entries

You can remove an entry from a nested dictionary using the del statement:

Example:

students = {
    "Amit": {"age": 21, "major": "Computer Science"},
    "Bala": {"age": 22, "major": "Mathematics"},
    "Chitra": {"age": 20, "major": "Physics"}
}

# Removing Bala's major
del students["Bala"]["major"]
print(students["Bala"])
print(students)

Output:

{'age': 22}
{'Amit': {'age': 21, 'major': 'Computer Science'}, 'Bala': {'age': 22}, 'Chitra': {'age': 20, 'major': 'Physics'}}

Iterating Through Dictionaries

Dictionaries are versatile and allow you to iterate through their contents in various ways. Let’s explore how to loop through keys, values, key-value pairs, and more.

Looping Through Keys

To loop through all the keys in a dictionary, you can use the keys() method or simply iterate over the dictionary itself.

Example:

student_ages = {"Amit": 21, "Bala": 22, "Chitra": 20}

# Using keys() method
for key in student_ages.keys():
    print(key)

# Directly iterating over the dictionary
for key in student_ages:
    print(key)

Output:

Amit
Bala
Chitra
Amit
Bala
Chitra

Looping Through Values

To loop through all the values in a dictionary, you can use the values() method.

student_ages = {"Amit": 21, "Bala": 22, "Chitra": 20}

for value in student_ages.values():
    print(value)

Output:

21
22
20

Looping Through Key-Value Pairs

If you want to loop through both keys and values, you should use the items() method, which returns key-value pairs as tuples.

Example:

student_ages = {"Amit": 21, "Bala": 22, "Chitra": 20}

for key, value in student_ages.items():
    print(f"{key} is {value} years old.")

Output:

Amit is 21 years old.
Bala is 22 years old.
Chitra is 20 years old.

Using enumerate()

The enumerate() function adds a counter to an iterable and returns it as an enumerate object. Although enumerate() is more commonly used with lists, it can be used with dictionaries to keep track of the iteration count.

Example:

student_ages = {"Amit": 21, "Bala": 22, "Chitra": 20}

for index, (key, value) in enumerate(student_ages.items()):
    print(f"{index}: {key} is {value} years old.")

Output:

0: Amit is 21 years old.
1: Bala is 22 years old.
2: Chitra is 20 years old.

Looping with Conditions

You can add conditions within your loops to filter out specific items. This is useful when you want to process only certain key-value pairs that meet specific criteria.

Example 1: Filtering Students Above a Certain Age

student_ages = {"Amit": 21, "Bala": 22, "Chitra": 20}

# Looping with a condition
for key, value in student_ages.items():
    if value > 21:
        print(f"{key} is older than 21.")

Output:

Bala is older than 21.

Example 2: Selecting Keys with Specific Conditions

student_grades = {"Amit": 85, "Bala": 78, "Chitra": 92, "Deepak": 60}

# Selecting students who passed
for key, value in student_grades.items():
    if value >= 70:
        print(f"{key} passed with a grade of {value}.")

Output:

Amit passed with a grade of 85.
Bala passed with a grade of 78.
Chitra passed with a grade of 92.

Merging Multiple Dictionaries

You often need to combine multiple dictionaries into one. There are several ways to achieve this:

Using the update() Method

The update() method adds the key-value pairs from one dictionary to another. If the same key exists in both dictionaries, the value from the second dictionary overwrites the first one.

Example:

dict1 = {"Amit": 21, "Bala": 22}
dict2 = {"Chitra": 20, "Deepak": 23}

dict1.update(dict2)
print(dict1)

Output:

{'Amit': 21, 'Bala': 22, 'Chitra': 20, 'Deepak': 23}

In this example, dict1 is updated with the contents of dict2. The final dictionary contains all key-value pairs from both dictionaries.

Using the ** Operator

The ** operator can unpack dictionaries and merge them into a new one. This method is concise and easy to read.

Example:

dict1 = {"Amit": 21, "Bala": 22}
dict2 = {"Chitra": 20, "Deepak": 23}

merged_dict = {**dict1, **dict2}
print(merged_dict)

Output:

{'Amit': 21, 'Bala': 22, 'Chitra': 20, 'Deepak': 23}

Using the | Operator

The | operator is another way to merge dictionaries, creating a new dictionary with items from both.

Example:

dict1 = {"Amit": 21, "Bala": 22}
dict2 = {"Chitra": 20, "Deepak": 23}

merged_dict = dict1 | dict2
print(merged_dict)

Output:

{'Amit': 21, 'Bala': 22, 'Chitra': 20, 'Deepak': 23}

Other Useful Methods

Python dictionaries come with several other useful methods. Now we’ll explore these methods:

setdefault()

The setdefault() method returns the value of a specified key. If the key does not exist, it inserts the key with a specified value.

Example:

student_ages = {"Amit": 21, "Bala": 22}

# Existing key
age_of_amit = student_ages.setdefault("Amit", 20)
print(age_of_amit)

# Non-existing key
age_of_chitra = student_ages.setdefault("Chitra", 20)
print(age_of_chitra)

print(student_ages)

Output:

21
20
{'Amit': 21, 'Bala': 22, 'Chitra': 20}

Dictionary Length

The len() function returns the number of key-value pairs in the dictionary. It’s a quick way to find out how many items are in your dictionary.

Example:

person = {'name': 'Aryan', 'age': 26, 'city': 'San Francisco'}

print(len(person))

Output:

3

Copying a Dictionary

The copy() method creates a shallow copy of the dictionary. This means it creates a new dictionary with the same key-value pairs, but it does not copy nested objects.

You can also create a copy of a dictionary using the dict() constructor.

Example:

person = {'name': 'Aryan', 'age': 26, 'city': 'San Francisco'}

# Using the copy() method
person_copy = person.copy()
print(person_copy)

# Using the dict() constructor
person_copy = dict(person)
print(person_copy)

Output:

{'name': 'Aryan', 'age': 26, 'city': 'San Francisco'}
{'name': 'Aryan', 'age': 26, 'city': 'San Francisco'}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *