Python Dictionary

A dictionary in Python is a built-in data type that stores data in key-value pairs. Each key must be unique and immutable (such as a string, number, or tuple), while values can be of any data type.

Creating a Dictionary

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 within the braces. Each key is separated from its value by a colon :, and individual pairs are separated by commas ,.

For example:

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

This code creates a dictionary named person with two key-value pairs: "name" set to the string "James" and "age" set to the integer 30.

Using The dict() Constructor

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

For example:

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

Accessing Dictionary Items

You can access dictionary items in Python using the square brackets or the get() method.

Using Square Brackets

To get a value from a dictionary, write the dictionary name, then put the key inside square brackets.

For example:

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

print(person["name"]) # Output: James
print(person["age"])  # age: 30

Using The get() Method

To get a value using the get() method, write the dictionary name followed by .get() with the key in parentheses. This is safer than using square brackets, as it returns None instead of raising a KeyError if the key is not found.

For example:

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

print(person.get("name")) # Output: James
print(person.get("age"))  # Output: 30

Adding Key-Value Pair to a Dictionary

Here are the two common ways to add key-value pairs to a dictionary.

Using Square Brackets

To add a new key-value pair to a dictionary, write the dictionary name, then use square brackets with the new key, and assign it a value using =. If the key already exists, its value will be updated.

For example:

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

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

Using The update() Method

The update() method allows you to add or update multiple key-value pairs to a dictionary from another dictionary or an iterable of key-value pairs.

To add key-value pairs using the update() method, write the dictionary name, then call .update() with the new pairs inside curly braces. If the key already exists, its value will be updated.

For example:

person = {"name": "James"}

person.update({"location": "London", "hobby": "dancing"})
print(person) # Output: {'name': 'James', 'location': 'London', 'hobby': 'dancing'}

Updating The Value of a Dictionary

You can change the value of an existing key in a dictionary by using square brackets or the update() method.

Using Square Brackets

To update a dictionary value, write the dictionary name, then use square brackets with the key you want to change and set it equal to the new value.

For example:

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

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

Using The update() Method

The update() method also allows you to modify multiple key-value pairs in a dictionary from another dictionary or an iterable of key-value pairs.

To update the values of a dictionary, write the dictionary name, then call .update() with the keys and their new values inside curly braces. If a specified key doesn’t exist in the dictionary, it will be added with its corresponding value.

For example:

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

person.update({"name": "Jack", "age": 55, "location": "London"})
print(person) # Output: {'name': 'Jack', 'age': 55, 'location': 'London'}

Remove a Key-Value Pair From a Dictionary

You can remove a key-value pair from a dictionary by using the del keyword or the pop() method.

Using The del Keyword

The del keyword lets you remove a specific key-value pair from a dictionary. If the key is not found, it will raise a KeyError.

To remove a key-value pair using the del keyword, write del followed by the dictionary name and the key inside square brackets.

For example:

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

del person["age"]
print(person) # Output: {'name': 'James'}

Using The pop() Method

The pop() method removes and returns the value for a given key. If the key is missing, it raises a KeyError unless you provide a default value.

To remove a key-value pair using the pop() method, write the dictionary name followed by .pop() with the key you want to remove inside parentheses.

For example:

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

person_age = person.pop("age")
print(person_age) # Output: 30
print(person)     # Output: {'name': 'James'}

Check If a Key Exists in a Dictionary

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

For example:

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

# Check if the key 'age' exists in the dictionary
if "age" in person:
    # It is exists, remove the key 'age' and its value from the dictionary
    del person["age"]
    
print(person) # {'name': 'James'}

Python Dictionary Methods

Python offers several built-in methods to manipulate key-value pairs. We have explored methods like get(), update() and pop(). Below is a table listing 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+).