Python Dictionary

A dictionary in Python is a built-in data type that stores data in key-value pairs. Each key is associated with a value where the key must be unique and immutable (string, number, or tuple), whereas the value can be of any data type.

Dictionaries are commonly used for tasks such as storing user information (e.g., name, age, and city) and managing inventories (e.g., item name, color, quantity, and price) on e-commerce platforms.

Dictionaries are widely used in programming because they store data in an organized way and let you quickly find values using keys.

Create a Dictionary

In Python, you can create a dictionary using either curly braces {} or the dict() constructor.

Using curly braces

To create a dictionary using curly braces {}, you enclose key:value pairs separated by commas inside them.

For example:

person = {"name": "James", "age": 40}

The dictionary person stores two key-value pairs: name with the value James and age with the value 40.

Using the dict() constructor

To create a dictionary using the dict() constructor, you pass key-value pairs as keyword arguments.

For example:

person = dict(name="James", age=40)

Access Dictionary Items

You can access the value of the key using the square brackets or the get() method.

Using square brackets

To retrieve the value of a key, write the dictionary name followed by the key inside square brackets.

For example:

person = {"name": "James", "age": 40, "city": "London"}

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

Output:

James
40

Using the get() method

The get() method provides a safer way to access dictionary items, as it doesn’t raise KeyError if the key doesn’t exist. Instead, it returns the specified default value if the key is not found, or None if no default is provided.

For example:

person = {"name": "James", "age": 40, "city": "London"}

city = person.get("city")
print(city) # London

job = person.get("job", "Not available")
print(job) # Not available

salary = person.get("salary")
print(salary) # None

Add an Item to a Dictionary

To add a new key-value pair to a dictionary, write the dictionary name followed by the new key inside square brackets and assign it a value. If the key already exists, the value will be updated with the new one.

For example:

person = {"name": "James", "age": 40}

person["city"] = "London"
print(person) # Output: {'name': 'James', 'age': 40, 'city': 'London'}

Update a Dictionary Value

To update values in a dictionary, you can either use square brackets or the update() method.

Using square brackets

To update or modify the value of an existing key in a dictionary, specify the dictionary name followed by a key in square brackets and assign a new value. If the key doesn’t exist, a new key-value pair will be added.

For example:

person = {"name": "James", "age": 40, "city": "London"}

# Updating the value of 'city' to 'Paris'
person["city"] = "Paris"
print(person) # Output: {'name': 'James', 'age': 40, 'city': 'Paris'}

Using update() method

The update() method allows you to update one or more key-value pairs at once. If the key already exists, its value is updated. If the key doesn’t exist, a new key-value pair is added.

For example:

person = {"name": "James", "age": 40, "city": "London"}

# Update the values of 'age' and 'city', and insert a new key 'job' with the value 'pilot'
person.update({"age": 45, "city": "New York", "job": "pilot"})
print(person) # Output: {'name': 'James', 'age': 45, 'city': 'New York', 'job': 'pilot'}

Remove an Item from a Dictionary

To remove an item from a dictionary, you can use the del keyword or the pop() method.

Using the del keyword

The del keyword allows you to remove a specific key-value pair from a dictionary. If the key doesn’t exist, a KeyError will be raised.

For example:

person = {"name": "James", "age": 40, "city": "London"}

# Deleting the key 'age' 
del person["age"]

print(person) # Output: {'name': 'James', 'city': 'London'}

Using the pop() method

The pop() method removes and returns the value associated with the specified key. If the key doesn’t exist, a KeyError is raised unless a default value is provided.

For example:

person = {"name": "James", "age": 40, "city": "London"}

# Delete the key 'city' and retrieve its value
removed_value = person.pop("city")
print(removed_value) # Output: London

print(person) # Output: {'name': 'James', 'age': 40}

Using the clear() method

If you want to remove all key-value pairs from a dictionary, you can use the clear() method. This method empties the dictionary completely.

For example:

person = {"name": "James", "age": 40, "city": "London"}

# Clearing all key-value paris from the dictionary
person.clear()
print(person) # Ourput: {}

Iterate through a Dictionary

In Python, you can loop through a dictionary using several different methods. You can iterate over the keys, values, or key-value pairs.

Looping Through Keys

To loop through the keys of a dictionary, you can use the keys() method, which returns a view object of the dictionary’s keys.

For example:

person = {"name": "James", "age": 40, "city": "London"}

for key in person.keys():
    print(key)

Output:

name
age
city

You can also loop through a dictionary directly, as its default behavior is to iterate over the keys.

For example:

person = {"name": "James", "age": 40, "city": "London"}

for key in person:
    print(key)

Output:

name
age
city

Looping Through Values

To loop through the values of a dictionary, you can use the values() method, which returns a view object of the dictionary’s values.

For example:

person = {"name": "James", "age": 40, "city": "London"}

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

Output:

James
40
London

Looping Through Key-Value Pairs

To iterate through the key-value pairs of a dictionary, you can use the items() method, which returns a view object of the dictionary’s key-value pairs.

For example:

person = {"name": "James", "age": 40, "city": "London"}

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

Output:

name: James
age: 40
city: London

Check if the key exists in a Dictionary

You can use the in keyword to check if the key already exists in a dictionary.

For example:

my_dict = {"name": "James Bond", "age": 35, "city": "London"}

# Check if the key exists
if "name" in my_dict:
    print("Key 'name' Exists")
else:
    print("Key 'name' doesn't exist.")

Output:

Key 'name' Exists

When deleting a key, attempting to remove a non-existent key will raise KeyError. You can avoid this by first verifying that the key exists.

person = {"name": "James", "age": 40, "city": "London"}

if 'job' in person.keys():
    del person['job']
else:
    print("Key 'job' doesn't exist in the dictionary")

Output:

Key 'job' doesn't exist in the dictionary

Similarly, when modifying a value, if the key doesn’t exist in the dictionary, a new key-value pair will be added to the dictionary. If you want to prevent this, you can do so by checking if the key is already present before making any changes.

person = {"name": "James", "age": 40, "city": "London"}

# Checking if key 'job' is not present in the dictionary
if "job" not in person.keys():
    person["job"] = "singer"
else: 
    print("Key 'job' already exists in the dictionary")
    
print(person)

Output:

{'name': 'James', 'age': 40, 'city': 'London', 'job': 'singer'}

Python Dictionary Methods

Python provides several built-in dictionary methods for manipulating key-value pairs. Here is a table of all the dictionary methods:

MethodsDescription
get()Returns the value for the key safely. Avoids KeyError.
keys()Returns a view object with all dictionary keys.
values()Returns a view object with all dictionary values.
items()Returns a view object with all key-value pairs as tuples.
update()Updates the dictionary with key-value pairs from another dictionary, overwriting existing keys.
pop()Removes and returns the value of the specified key.
clear()Removes all items from the dictionary.
copy()Returns a shallow copy of the dictionary.
setdefault()Returns value of key if present, else inserts key with default value and returns default.
fromkeys()Create a new dictionary with keys from an iterable, all assigned the same specified value (or None if no value is specified).
popitem()Removes and returns the last inserted key-value pair as a tuple (LIFO order in Python 3.7+).