Skip to content

An Introduction to Dictionaries in Python

Updated: at 05:01 AM

Dictionaries are a fundamental data type in Python that store elements as key-value pairs. Unlike sequences like lists and tuples which store elements by numerical index, dictionaries allow you to organize data by associating unique keys with values. Dictionaries provide a flexible, unordered collection of elements that can be accessed, inserted, and removed efficiently.

In this comprehensive guide, we will cover everything you need to know as a Python programmer to start working with dictionaries effectively. We will examine how to create, access, modify, and manipulate dictionaries through examples. By the end, you will have a solid grasp of dictionary operations and be able to apply them in your Python code.

Table of Contents

Open Table of Contents

What are Dictionaries in Python?

A dictionary in Python is an unordered collection of objects that stores key-value pairs. The keys are used to access associated values from the dictionary. Dictionaries are mutable, meaning the contents can be modified after creation.

The keys in a dictionary must be unique and immutable objects like strings, numbers, or tuples. The values can be any arbitrary Python objects. Dictionaries allow for efficient lookup of values based on keys and are commonly used to implement lookup tables, counters, and similar data structures.

Here is the syntax to create a simple dictionary in Python:

my_dict = {
  'key1': 'value1',
  'key2': 'value2'
}

This creates a dictionary named my_dict with two key-value pairs mapping ‘key1’ to ‘value1’ and ‘key2’ to ‘value2’. The keys and values can be any objects.

Dictionary Operations and Methods

Now let’s explore the common dictionary operations and built-in methods available in Python:

Accessing Values

Values can be accessed by specifying keys in square brackets []:

my_dict = {'name': 'John', 'age': 25}

print(my_dict['name']) # Prints 'John'
print(my_dict['age']) # Prints 25

If a key is not found, a KeyError exception is raised. You can provide a default value instead using the .get() method:

print(my_dict.get('address')) # Prints None as key not found
print(my_dict.get('name')) # Prints 'John'

print(my_dict.get('address', 'Not found')) # Prints 'Not found' as default

Adding Items

New items can be added to a dictionary by specifying a new key and value:

my_dict['address'] = '123 Main St' # Add new key-value pair

print(my_dict) # {'name': 'John', 'age': 25, 'address': '123 Main St'}

The .update() method can update multiple key-value pairs from another dictionary:

new_data = {'city': 'Anytown', 'zip': 12345}
my_dict.update(new_data)

print(my_dict)
# {'name': 'John', 'age': 25, 'address': '123 Main St', 'city': 'Anytown', 'zip': 12345}

Modifying Values

Values can be modified by assigning to an existing key:

my_dict['age'] = 26 # Update existing key 'age'
print(my_dict) # {'name': 'John', 'age': 26, 'address': '123 Main St'}

Removing Items

The del keyword removes a key-value pair by key:

del my_dict['address']
print(my_dict) # {'name': 'John', 'age': 26}

The .pop() method removes and returns the value for a key:

age = my_dict.pop('age')
print(age) # 26
print(my_dict) # {'name': 'John'}

The .popitem() method removes and returns an arbitrary key-value pair:

item = my_dict.popitem()
print(item) # ('name', 'John')

print(my_dict) # Empty dict {}

To remove all items, use the .clear() method:

my_dict.clear()
print(my_dict) # {} Empty dict

Length and Membership

To check the length (number of items) in a dictionary, use the len() function:

print(len(my_dict)) # 3

To check if a key exists in the dictionary, use the in operator:

print('name' in my_dict) # True
print('address' in my_dict) # False

Iterating Over Dictionaries

You can loop through dictionary items using the .items() method which returns key-value tuples:

for key, value in my_dict.items():
  print(key, value)

# name John
# age 25
# address 123 Main St

To loop through just keys or just values, use .keys() and .values():

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

# name
# age
# address

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

# John
# 25
# 123 Main St

Copying Dictionaries

Dictionaries can be copied using the built-in .copy() method:

my_dict_copy = my_dict.copy()

This creates a shallow copy of the dictionary. Modifying elements in one copy will affect the other.

To create a deep copy, use copy.deepcopy():

import copy

my_dict_deepcopy = copy.deepcopy(my_dict)

Now the two dictionaries can be modified independently without affecting each other.

Dictionaries vs Lists and Tuples

Let’s compare some key differences between dictionaries and other Python data types like lists and tuples:

So in summary:

Common Dictionary Uses

Some common use cases where dictionaries shine in Python:

Lookup Tables

Dictionaries provide fast lookup performance on key search, making them ideal for implementing lookup tables:

ip_to_host = {
  '192.168.1.1': 'hostA',
  '192.168.1.2': 'hostB'
}

print(ip_to_host['192.168.1.1']) # Prints 'hostA'

Counters

Dictionaries can implement counter functionality where the keys are the items being counted and values are the counts:

letter_counts = {
  'a': 3,
  'b': 9,
  'c': 11
}

# Update counter
letter_counts['a'] += 1

print(letter_counts['a']) # Prints 4

Storing Configuration or Settings

Dictionaries provide a convenient way to store program configuration or settings:

config = {
  'host': '127.0.0.1',
  'port': 8080,
  'debug': True
}

print(config['debug']) # Prints True

Caching/Memoization

By storing results in a dictionary, expensive function calls can be avoided by first looking up in the cache:

# Store results in dict to cache
cache = {}

def fibonacci(n):
  if n in cache:
    return cache[n]

  # Compute and cache
  cache[n] = compute_fib(n)
  return cache[n]

This allows speeding up programs by caching slow function call results.

Dictionaries as Key-Value Stores in Databases

Dictionaries in Python provide a convenient in-memory key-value store. This makes them similar to NoSQL databases which also use key-value pairs for storage and fast lookup.

Python dictionaries are however limited to memory and are not designed for large persistent datasets. For that, databases like Redis and MongoDB are better suited. They provide persistent on-disk storage, support for large datasets, and additional features like replication, transactions, and clustering.

The dictionary interface in Python can be useful when translating data from key-value databases. For example, with Redis:

import redis

r = redis.Redis(...)

user = {
  'name': r.get('user:1000:name'),
  'age': r.get('user:1000:age'),
  'visits': int(r.get('user:1000:visits'))
}

print(user['name'])

Here we fetch key-value data from Redis and create a dictionary to represent a user entity. The dictionary provides a convenient interface to work with the data in Python.

Best Practices for Working with Dictionaries

Here are some tips for working effectively with dictionaries in Python:

Conclusion

Dictionaries are a versatile built-in data type in Python that allow you to work with key-value associations. They provide fast lookup and insertion performance, making them ideal for use cases like tables, configurations, caching, and more.

The dictionary interface in Python is also conceptually similar to the key-value databases like Redis and MongoDB. Mastering dictionary usage unlocks the ability to process and leverage data from such databases efficiently.

With this comprehensive guide, you should now feel confident with all aspects of Python dictionary manipulation - from basic operations to advanced techniques. Equipped with this knowledge, you can effectively apply dictionaries in your Python code.

Happy coding!