Contents

Dictionaries in Python

Exploring Python's Dictionary Data Structure: Properties, Methods, and Real-world Examples

Website Visitors:

Dictionaries in Python: An In-depth Guide

Dictionaries in Python are an essential data structure that allows you to store and retrieve data using key-value pairs. Unlike sequences such as lists or tuples, dictionaries are unordered and use keys instead of indices to access values. In this article, we’ll explore the concept of dictionaries in Python, their properties, methods, and various use cases with detailed examples.

Creating a Dictionary

To create a dictionary in Python, you can use curly braces {} or the dict() constructor. Let’s start with some basic examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Empty dictionary
empty_dict = {}
print(empty_dict)  # Output: {}

# Dictionary with initial values
person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}
print(person)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

# Using the dict() constructor
employee = dict(name='Jane', age=25, city='London')
print(employee)  # Output: {'name': 'Jane', 'age': 25, 'city': 'London'}

Accessing Dictionary Values

To access values in a dictionary, you can use the keys as indices. If a key doesn’t exist, it will raise a KeyError. Alternatively, you can use the get() method, which returns None or a default value if the key doesn’t exist.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

print(person['name'])  # Output: John
print(person.get('age'))  # Output: 30
print(person.get('country'))  # Output: None
print(person.get('country', 'USA'))  # Output: USA

Modifying and Adding Dictionary Entries

Dictionaries are mutable, which means you can modify their values and add new key-value pairs. Here’s how you can modify and add entries to a dictionary:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# Modifying values
person['age'] = 35
print(person)  # Output: {'name': 'John', 'age': 35, 'city': 'New York'}

# Adding new entries
person['country'] = 'USA'
print(person)  # Output: {'name': 'John', 'age': 35, 'city': 'New York', 'country': 'USA'}

Dictionary Methods

Python dictionaries come with various built-in methods to perform common operations. Here are a few essential methods:

keys(): Returns a view object containing all the keys in the dictionary.

1
2
3
4
5
6
7
person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

print(person.keys())  # Output: dict_keys(['name', 'age', 'city'])

values(): Returns a view object containing all the values in the dictionary.

1
2
3
4
5
6
7
person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

print(person.values())  # Output: dict_values(['John', 30, 'New York'])
1
2
3
4
5
6
7
count = {"jpg":10,"csv":44,"exe":33}

for value in count.values():
    print(value)
    
for key in count.keys():
    print(key)
1
2
3
4
count = {"jpg":10,"csv":44,"exe":33}

print(count.keys())
print(count.values())

items(): Returns a view object containing all the key-value pairs as tuples.

Example 1:

1
2
3
4
5
6
7
person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

print(person.items())  # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])

Example 2:

1
2
3
4
5
6
7
8
9
count = {"jpg":10,"csv":44,"exe":33}

for number,extension in count.items():
    print("Extension is {} and its number is {}".format(extension,number))

# Output:
Extension is 10 and its number is jpg
Extension is 44 and its number is csv
Extension is 33 and its number is exe

pop(): Removes and returns the value associated with a given key. If the key doesn’t exist, it will raise a KeyError.

1
2
3
4
5
6
7
8
9
person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

age = person.pop('age')
print(age)  # Output: 30
print(person)  # Output: {'name': 'John', 'city': 'New York'}

del(): Deletes a dictionary key pair value from the dictionary.

1
2
3
4
5
my_dict = {"jpg":10,"png":2}
del my_dict["jpg"]
my_dict

# Output {'png': 2}

update(): Updates a dictionary with the key-value pairs from another dictionary or an iterable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
person = {
    'name': 'John',
    'age': 30,
}

extra_info = {
    'city': 'New York',
    'country': 'USA'
}

person.update(extra_info)
print(person)  # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}

Dictionary Iteration

You can iterate over a dictionary’s keys, values, or key-value pairs using a loop. Here’s how you can do it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# Iterating over keys
for key in person:
    print(key)

# Iterating over values
for value in person.values():
    print(value)

# Iterating over key-value pairs
for key, value in person.items():
    print(key, value)

Dictionary Comprehension

Similar to list comprehensions, you can also create dictionaries using dictionary comprehensions. It provides a concise way to create dictionaries based on an expression and an optional condition. Here’s an example:

1
2
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Conclusion

Dictionaries in Python are powerful data structures that provide a flexible way to store and retrieve data using key-value pairs. Understanding how dictionaries work and utilizing their methods can greatly enhance your Python programming skills. In this article, we covered the basics of dictionaries, including creation, accessing values, modifying entries, important methods, iteration, and dictionary comprehensions. With this knowledge, you’ll be able to effectively use dictionaries in various real-world scenarios.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.