Skip to content

Dictionaries in Python

Mastering Dictionaries in Python: A Comprehensive Guide

Dictionaries in Python are powerful and flexible data structures that allow you to store and retrieve data in key-value pairs. They are an essential part of the Python language, providing an efficient way to organize and manipulate data. In this comprehensive guide, we will explore the fundamentals of dictionaries, how to create and manipulate them, common operations, and practical use cases where dictionaries shine.

Understanding Dictionaries

A dictionary in Python is an unordered collection of items, where each item consists of a key-value pair. Keys are unique and used to access values associated with them. Dictionaries are dynamic, meaning you can add, modify, or remove key-value pairs as needed.

Creating Dictionaries

There are several ways to create dictionaries in Python. The most common way is to use curly braces {}{} and separate key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. The following example creates a dictionary with three key-value pairs:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1)
dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}
command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}

In this example, we create a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary contains three key-value pairs.

You can also create dictionaries using the dict()dict() constructor. The following example creates a dictionary with three key-value pairs:

dict.py
dict1 = dict(name="John", age=30, city="New York")
print(dict1)
dict.py
dict1 = dict(name="John", age=30, city="New York")
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}
command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}

In this example, we create a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary contains three key-value pairs.

Properties of Dictionaries

Dictionaries in Python have the following properties:

  • Unordered: Dictionaries are unordered, meaning that the order of key-value pairs is not preserved. When you print a dictionary, the order of key-value pairs may change. This is because dictionaries are implemented using hash tables, which are unordered data structures.
  • Mutable: Dictionaries are mutable, meaning that you can add, modify, or remove key-value pairs as needed.
  • Dynamic: Dictionaries are dynamic, meaning that you can add, modify, or remove key-value pairs as needed.
  • Unique Keys: Dictionary keys must be unique. If you try to create a dictionary with duplicate keys, the last key-value pair will overwrite the previous one.
  • Key-Value Pairs: Dictionaries are key-value pairs, meaning that each item consists of a key and a value separated by a colon ::.
  • Keys: Dictionary keys can be any immutable data type, such as strings, numbers, or tuples. Dictionary keys must be unique.
  • Values: Dictionary values can be any data type, such as strings, numbers, lists, or tuples. Dictionary values can be duplicates.
  • Length: The length of a dictionary is the number of key-value pairs it contains. You can use the len()len() function to get the length of a dictionary.
  • Access: You can access dictionary items by their keys. If you try to access a key that does not exist, you will get a KeyErrorKeyError exception.
  • Membership: You can check if a key exists in a dictionary using the inin operator. If you try to check if a key that does not exist, you will get a KeyErrorKeyError exception.
  • Iteration: You can iterate over a dictionary using a forfor loop. When you iterate over a dictionary, you get the keys of the dictionary.
  • Copying: You can copy a dictionary using the copy()copy() method. The copy is a shallow copy, meaning that the keys and values are not copied.

Declaring Dictionaries

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. The following example declares a dictionary with three key-value pairs:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1)
dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}
command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}

In this example, we declare a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary contains three key-value pairs.

Declaring Empty Dictionaries

You can declare empty dictionaries in Python using curly braces {}{}. The following example declares an empty dictionary:

dict.py
dict1 = {}
print(dict1)
dict.py
dict1 = {}
print(dict1)

Output:

command
C:\Users\username>python dict.py
{}
command
C:\Users\username>python dict.py
{}

In this example, we declare an empty dictionary and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary is empty.

Declaring Dictionaries with the dict() Constructor

You can also declare dictionaries in Python using the dict()dict() constructor. The following example declares a dictionary with three key-value pairs:

dict.py
dict1 = dict(name="John", age=30, city="New York")
print(dict1)
dict.py
dict1 = dict(name="John", age=30, city="New York")
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}
command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}

In this example, we declare a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary contains three key-value pairs.

Declaring a Dictionary with Elements

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. The following example declares a dictionary with three key-value pairs:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1)
dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}
command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}

In this example, we declare a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary contains three key-value pairs.

Declaring a Dictionary with Duplicate Keys

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. The following example declares a dictionary with three key-value pairs:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York", "name": "Jane"}
print(dict1)
dict.py
dict1 = {"name": "John", "age": 30, "city": "New York", "name": "Jane"}
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'Jane', 'age': 30, 'city': 'New York'}
command
C:\Users\username>python dict.py
{'name': 'Jane', 'age': 30, 'city': 'New York'}

In this example, we declare a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary contains three key-value pairs.

Declaring a Dictionary with Elements of Different Data Types

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. The following example declares a dictionary with three key-value pairs:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York", "grades": [90, 80, 70]}
print(dict1)
dict.py
dict1 = {"name": "John", "age": 30, "city": "New York", "grades": [90, 80, 70]}
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York', 'grades': [90, 80, 70]}
command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York', 'grades': [90, 80, 70]}

In this example, we declare a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary contains three key-value pairs.

Declaring a Dictionary with Multiple Lines

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. The following example declares a dictionary with three key-value pairs:

dict.py
dict1 = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
print(dict1)
dict.py
dict1 = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}
command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}

In this example, we declare a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary contains three key-value pairs.

Declaring a Dictionary with Multiple Lines using the dict() Constructor

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. The following example declares a dictionary with three key-value pairs:

dict.py
dict1 = dict(
    name="John",
    age=30,
    city="New York"
)
print(dict1)
dict.py
dict1 = dict(
    name="John",
    age=30,
    city="New York"
)
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}
command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York'}

In this example, we declare a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary contains three key-value pairs.

Declaring a Dictionary with Collections

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. The following example declares a dictionary with three key-value pairs:

dict.py
dict1 = {
    "name": "John",
    "age": 30,
    "city": "New York",
    "grades": [90, 80, 70],
    "friends": ("Jane", "Jack", "Joe"),
    "pets": {"dog": "Spot", "cat": "Fluffy"}
}
print(dict1)
dict.py
dict1 = {
    "name": "John",
    "age": 30,
    "city": "New York",
    "grades": [90, 80, 70],
    "friends": ("Jane", "Jack", "Joe"),
    "pets": {"dog": "Spot", "cat": "Fluffy"}
}
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York', 'grades': [90, 80, 70], 'friends': ('Jane', 'Jack', 'Joe'), 'pets': {'dog': 'Spot', 'cat': 'Fluffy'}}
command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York', 'grades': [90, 80, 70], 'friends': ('Jane', 'Jack', 'Joe'), 'pets': {'dog': 'Spot', 'cat': 'Fluffy'}}

In this example, we declare a dictionary with six key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary contains six key-value pairs.

Declaring a Dictionary with Collections as Keys

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. The following example declares a dictionary with three key-value pairs:

dict.py
dict1 = {
    "name": "John",
    "age": 30,
    "city": "New York",
    ("dog", "cat"): "pets"
}
print(dict1)
dict.py
dict1 = {
    "name": "John",
    "age": 30,
    "city": "New York",
    ("dog", "cat"): "pets"
}
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York', ('dog', 'cat'): 'pets'}
command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York', ('dog', 'cat'): 'pets'}

In this example, we declare a dictionary with four key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that the dictionary contains four key-value pairs.

Declaring a Dictionary with Collections as Unhashable Keys

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. If you try to declare a dictionary with unhashable keys, you will get a TypeErrorTypeError exception. The following example declares a dictionary with three key-value pairs:

dict.py
dict1 = {
    "name": "John",
    "age": 30,
    "city": "New York",
    ["dog", "cat"]: "pets"
}
print(dict1)
dict.py
dict1 = {
    "name": "John",
    "age": 30,
    "city": "New York",
    ["dog", "cat"]: "pets"
}
print(dict1)

Output:

command
C:\Users\username>python dict.py
Traceback (most recent call last):
  File "dict.py", line 4, in <module>
    ["dog", "cat"]: "pets"
TypeError: unhashable type: 'list'
command
C:\Users\username>python dict.py
Traceback (most recent call last):
  File "dict.py", line 4, in <module>
    ["dog", "cat"]: "pets"
TypeError: unhashable type: 'list'

In this example, we try to declare a dictionary with four key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that we get a TypeErrorTypeError exception because we tried to declare a dictionary with unhashable keys.

Declaring a Dictionary using List

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. If you try to declare a dictionary with a list, you will get a TypeErrorTypeError exception. The following example declares a dictionary with three key-value pairs:

dict.py
data = ["name", "John", "age", 30, "city", "New York"]
dict1 = {data}
print(dict1)
dict.py
data = ["name", "John", "age", 30, "city", "New York"]
dict1 = {data}
print(dict1)

Output:

command
C:\Users\username>python dict.py
Traceback (most recent call last):
  File "dict.py", line 2, in <module>
    dict1 = {data}
TypeError: unhashable type: 'list'
command
C:\Users\username>python dict.py
Traceback (most recent call last):
  File "dict.py", line 2, in <module>
    dict1 = {data}
TypeError: unhashable type: 'list'

In this example, we try to declare a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that we get a TypeErrorTypeError exception because we tried to declare a dictionary with a list.

Declaring a Dictionary using Tuple

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. If you try to declare a dictionary with a tuple, you will get a TypeErrorTypeError exception. The following example declares a dictionary with three key-value pairs:

dict.py
data = ("name", "John", "age", 30, "city", "New York")
dict1 = {data}
print(dict1)
dict.py
data = ("name", "John", "age", 30, "city", "New York")
dict1 = {data}
print(dict1)

Output:

command
C:\Users\username>python dict.py
Traceback (most recent call last):
  File "dict.py", line 2, in <module>
    dict1 = {data}
TypeError: unhashable type: 'tuple'
command
C:\Users\username>python dict.py
Traceback (most recent call last):
  File "dict.py", line 2, in <module>
    dict1 = {data}
TypeError: unhashable type: 'tuple'

In this example, we try to declare a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that we get a TypeErrorTypeError exception because we tried to declare a dictionary with a tuple.

Declaring a Dictionary using Set

You can declare dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. If you try to declare a dictionary with a set, you will get a TypeErrorTypeError exception. The following example declares a dictionary with three key-value pairs:

dict.py
data = {"name", "John", "age", 30, "city", "New York"}
dict1 = {data}
print(dict1)
dict.py
data = {"name", "John", "age", 30, "city", "New York"}
dict1 = {data}
print(dict1)

Output:

command
C:\Users\username>python dict.py
Traceback (most recent call last):
  File "dict.py", line 2, in <module>
    dict1 = {data}
TypeError: unhashable type: 'set'
command
C:\Users\username>python dict.py
Traceback (most recent call last):
  File "dict.py", line 2, in <module>
    dict1 = {data}
TypeError: unhashable type: 'set'

In this example, we try to declare a dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the dictionary to the console. The output shows that we get a TypeErrorTypeError exception because we tried to declare a dictionary with a set.

Declaring a Nested Dictionary

You can declare nested dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. The following example declares a nested dictionary with three key-value pairs:

dict.py
dict1 = {
    "name": "John",
    "age": 30,
    "city": "New York",
    "grades": [90, 80, 70],
    "friends": ("Jane", "Jack", "Joe"),
    "pets": {"dog": "Spot", "cat": "Fluffy"}
}
print(dict1["pets"])
dict.py
dict1 = {
    "name": "John",
    "age": 30,
    "city": "New York",
    "grades": [90, 80, 70],
    "friends": ("Jane", "Jack", "Joe"),
    "pets": {"dog": "Spot", "cat": "Fluffy"}
}
print(dict1["pets"])

Output:

command
C:\Users\username>python dict.py
{'dog': 'Spot', 'cat': 'Fluffy'}
command
C:\Users\username>python dict.py
{'dog': 'Spot', 'cat': 'Fluffy'}

In this example, we declare a nested dictionary with six key-value pairs and assign it to the variable dict1dict1. We then print the value of the key petspets to the console. The output shows that the value of the key is {'dog': 'Spot', 'cat': 'Fluffy'}{'dog': 'Spot', 'cat': 'Fluffy'}.

Declaring a Dictionary with Nested Tuple

You can declare nested dictionaries in Python using curly braces {}{} and separating key-value pairs with commas. Each key-value pair consists of a key and a value separated by a colon ::. The following example declares a nested dictionary with three key-value pairs:

dict.py
dict1 = dict([("name", "John"), ("age", 30), ("city", "New York")])
print(dict1["name"])
dict.py
dict1 = dict([("name", "John"), ("age", 30), ("city", "New York")])
print(dict1["name"])

Output:

command
C:\Users\username>python dict.py
John
command
C:\Users\username>python dict.py
John

In this example, we declare a nested dictionary with three key-value pairs and assign it to the variable dict1dict1. We then print the value of the key namename to the console. The output shows that the value of the key is JohnJohn.

Accessing Dictionary Items

You can access dictionary items by their keys. If you try to access a key that does not exist, you will get a KeyErrorKeyError exception.

Accessing a Key that Exists

You can access dictionary items by their keys. The following example accesses the key namename of the dictionary dict1dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1["name"])
dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1["name"])

Output:

command
C:\Users\username>python dict.py
John
command
C:\Users\username>python dict.py
John

In this example, we access the key namename of the dictionary dict1dict1. We then print the value of the key to the console. The output shows that the value of the key is JohnJohn.

Accessing a Key using the get() Method

You can access dictionary items by their keys using the get()get() method. If you try to access a key that does not exist, you will get NoneNone. The following example accesses the key namename of the dictionary dict1dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1.get("name"))
dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1.get("name"))

Output:

command
C:\Users\username>python dict.py
John
command
C:\Users\username>python dict.py
John

In this example, we access the key namename of the dictionary dict1dict1. We then print the value of the key to the console. The output shows that the value of the key is JohnJohn.

Accessing a Key that Does Not Exist using the get() Method

You can access dictionary items by their keys using the get()get() method. If you try to access a key that does not exist, you will get NoneNone. The following example accesses a key that does not exist:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1.get("address"))
dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1.get("address"))

Output:

command
C:\Users\username>python dict.py
None
command
C:\Users\username>python dict.py
None

In this example, we try to access the key addressaddress of the dictionary dict1dict1. We then print the value of the key to the console. The output shows that we get NoneNone because the key does not exist.

Length of a Dictionary

The length of a dictionary is the number of key-value pairs it contains. You can use the len()len() function to get the length of a dictionary. The following example gets the length of the dictionary dict1dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(len(dict1))
dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(len(dict1))

Output:

command
C:\Users\username>python dict.py
3
command
C:\Users\username>python dict.py
3

In this example, we get the length of the dictionary dict1dict1. We then print the length of the dictionary to the console. The output shows that the length of the dictionary is 33.

Iterating Over a Dictionary

You can iterate over a dictionary using a forfor loop. When you iterate over a dictionary, you get the keys of the dictionary. The following example iterates over the dictionary dict1dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
for key in dict1:
    print(key + " => " + str(dict1[key]))
dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
for key in dict1:
    print(key + " => " + str(dict1[key]))

Output:

command
C:\Users\username>python dict.py
name => John
age => 30
city => New York
command
C:\Users\username>python dict.py
name => John
age => 30
city => New York

In this example, we iterate over the dictionary dict1dict1. We then print the keys and values of the dictionary to the console. The output shows that we get the keys of the dictionary.

Conclusion

Dictionaries in Python are powerful and flexible data structures that allow you to store and retrieve data in key-value pairs. They are an essential part of the Python language, providing an efficient way to organize and manipulate data. In this comprehensive guide, we explored the fundamentals of dictionaries, how to create and manipulate them, common operations, and practical use cases where dictionaries shine. For more information on dictionaries, check out the official documentation. For more tutorials on Python, check out the Python Central Hub.


Try it: Python Dictionary Exercises

Exercise 1 – Create and Access

Exercise 2 – Iterate over Items

Exercise 3 – Dictionary Length and Keys

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did