What is a Dictionary in Python and How to Use it?

Vilashkumar
4 min readJan 16, 2024

--

Dictionaries are one of the fundamental data structures in Python. They are versatile and powerful tools for storing and manipulating data, and they play a crucial role in many Python applications.

In this blog, we’ll explore Python dictionaries in detail, covering their basic syntax, common operations, and some advanced techniques.

What Is a Dictionary?

In Python, a dictionary is a collection of key-value pairs, where each key is unique and maps to a specific value. Dictionaries are unordered, which means that the order of the elements is not guaranteed. They are commonly used to store and retrieve data efficiently, especially when you need fast lookups based on keys.

Creating a Dictionary

You can create a dictionary by enclosing a comma-separated list of key-value pairs within curly braces {}. Each key-value pair is separated by a colon :. Here’s an example of creating a simple dictionary:

my_dict = {"name": "John", "age": 30, "city": "New York"}

In this example, my_dict is a dictionary with three key-value pairs. The keys are "name", "age", and "city", and the corresponding values are "John", 30, and "New York".

Accessing Values from Dictionary

To access the values in a dictionary, you can use the square brackets [] and provide the key. For example:

name = my_dict["name"]

The name variable now holds the value "John". If the key does not exist in the dictionary, it will raise a KeyError. To avoid this, you can use the get() method:

name = my_dict.get("name")

The get() method returns None if the key is not found you can specify a default value as the second argument:

name = my_dict.get("name", "Unknown")

Now, if the key "name" does not exist, name will be set to "Unknown".

Modifying and Adding Elements in Dictionary

Dictionaries are mutable, which means you can modify their contents. To change the value associated with a key, simply assign a new value to that key:

my_dict["age"] = 31

To add a new key-value pair, use the square brackets with a key that doesn’t exist in the dictionary:

my_dict["country"] = "USA"

Now, the dictionary my_dict has a new key "country" with the value "USA".

Removing Elements from Dictionary

You can remove key-value pairs from a dictionary using the del statement. For example, to remove the "city" key and its corresponding value:

del my_dict["city"]

Alternatively, you can use the pop() method, which not only removes the item but also returns its value:

removed_value = my_dict.pop("city")

Important Dictionary Methods

Python dictionaries come with a variety of built-in methods that allow you to perform common operations:

keys():

This method returns a list of all the keys in the dictionary.

my_dict = {"name": "John", "age": 30, "city": "New York"}
keys_list = my_dict.keys()
print(keys_list)
# Output: dict_keys(['name', 'age', 'city'])

values():

It returns a list of all the values in the dictionary.

my_dict = {"name": "John", "age": 30, "city": "New York"}
values_list = my_dict.values()
print(values_list)
# Output: dict_values(['John', 30, 'New York'])

items():

The items() method returns a list of key-value pairs as tuples.

my_dict = {"name": "John", "age": 30, "city": "New York"}
items_list = my_dict.items()
print(items_list)
# Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])

clear():

This method is used to remove all key-value pairs from the dictionary.

my_dict = {"name": "John", "age": 30, "city": "New York"}
my_dict.clear()
print(my_dict)
# Output: {}

copy():

This method creates a shallow copy of the dictionary. The shallow copy means, that if you change the value from the copied dictionary, then the original dictionary will not update its value. For example,

original_dict = {"name": "John", "age": 30, "city": "New York"}
copied_dict = original_dict.copy()
print(copied_dict)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}

update():

The update method is used to merge the contents of one dictionary into another.

dict1 = {"name": "John", "age": 30}
dict2 = {"city": "New York", "country": "USA"}
dict1.update(dict2)
print(dict1)
# Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}

Iterating Over Dictionaries

You can loop through the keys, values, or key-value pairs of a dictionary using a for loop. Here’s how you can iterate over the keys and values:

for key in my_dict:
value = my_dict[key]
print(f"{key}: {value}")

Or, you can use the items() method to directly iterate over key-value pairs:

for key, value in my_dict.items():
print(f"{key}: {value}")

Dictionary Comprehensions

Just like with lists and sets, you can use dictionary comprehension to create dictionaries concisely and elegantly. Here’s an example that creates a dictionary of squares:

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

Nested Dictionaries

Dictionaries can be nested within each other to create more complex data structures. This is useful for representing hierarchical or structured data. For instance, you can create a dictionary to represent a person’s information, including contact details:

person = {
"name": "Alice",
"age": 28,
"contact": {
"email": "alice@example.com",
"phone": "123-456-7890"
}
}

You can access nested values using multiple square brackets:

email = person["contact"]["email"]

Merge Dictionaries with |

Python 3.9 introduces the use of the | and |= operators for merging mappings, which is quite intuitive as these operators also serve as set union operators. For example,

Read More

--

--