Skip to content
Home / Fundamentals

Python Dictionary

Why use dictionaries in Python?

Dictionaries are a built-in data type in Python that allow you to store data as key-value pairs. They are similar to lists in that they can store multiple values, but unlike lists, they are not ordered and do not use integer indices. Instead, they use keys, which can be any immutable data type (such as strings, integers, or tuples). This makes dictionaries very useful for storing and accessing data quickly, especially when the data has some logical connection or meaning.

Real life example where dictionaries can be used

Here is an example of how you might use a dictionary in a real-life scenario:

Imagine you are building a small application to keep track of your friends' contact information. You could create a dictionary for each person, with the person's name as the key and their contact information (such as phone number and email address) as the value. This way, you can easily look up a person's contact information by their name, rather than having to search through a list of contacts or use a complex data structure.

Here is some sample code that demonstrates this concept:

# Create a dictionary for each person
person_1 = {'name': 'John Smith', 'phone': '123-456-7890', 'email': '[email protected]'}
person_2 = {'name': 'Jane Doe', 'phone': '987-654-3210', 'email': '[email protected]'}

# Add the dictionaries to a list
contacts = [person_1, person_2]

# Look up Jane's contact information
for contact in contacts:
    if contact['name'] == 'Jane Doe':
        print(f"Phone: {contact['phone']}")
        print(f"Email: {contact['email']}")

Syntax

Here is the syntax for creating and working with dictionaries in Python:

# Create an empty dictionary
dictionary = {}

# Create a dictionary with key-value pairs
dictionary = {'key_1': 'value_1', 'key_2': 'value_2', 'key_3': 'value_3'}

# Access a value by its key
value = dictionary['key_1']

# Add a new key-value pair to the dictionary
dictionary['key_4'] = 'value_4'

# Modify an existing value in the dictionary
dictionary['key_1'] = 'new_value'

# Remove a key-value pair from the dictionary
del dictionary['key_1']

Dictionary characteristics

Here are some characteristics of dictionaries in Python:

Dictionaries are usually considered unordered (they are ordered since Python 3.6). They do not have a fixed order and the keys and values may be rearranged when the dictionary is modified. Dictionaries use keys to access values, rather than integer indices. The keys can be any immutable data type, such as strings, integers, or tuples.

# Create a dictionary with key-value pairs
dictionary = {'key_1': 'value_1', 'key_2': 'value_2', 'key_3': 'value_3'}

# Access a value by its key
value = dictionary['key_1']
print(value)  # Output: 'value_1'

# You can also use the get() method to access a value
value = dictionary.get('key_1')
print(value)  # Output: 'value_1'

Dictionaries can store any data type as a value, including lists, other dictionaries, and even objects.

# Create a dictionary with a list as a value
dictionary = {'key': [1, 2, 3, 4]}

# Access the list by its key
value = dictionary['key']
print(value)  # Output: [1, 2, 3, 4]

# Create a dictionary with another dictionary as a value
dictionary = {'key': {'subkey': 'value'}}

# Access the nested dictionary by its key
value = dictionary['key']
print(value)  # Output: {'subkey': 'value'}

# Create a dictionary with an object as a value
class MyClass:
    def __init__(self, value):
        self.value = value

dictionary = {'key': MyClass('value')}

# Access the object by its key
value = dictionary['key']
print(value)  # Output: <__main__.MyClass object at 0x7f84e0f7d310>

Dictionaries are mutable. You can add, modify, or remove key-value pairs from a dictionary.

# Create an empty dictionary
dictionary = {}

# Add a new key-value pair to the dictionary
dictionary['key_1'] = 'value_1'
print(dictionary)  # Output: {'key_1': 'value_1'}

# Modify an existing value in the dictionary
dictionary['key_1'] = 'new_value'
print(dictionary)  # Output: {'key_1': 'new_value'}

# Remove a key-value pair from the dictionary
del dictionary['key_1']
print(dictionary)  # Output: {}

Best practices

Here are some best practices for using dictionaries in Python:

  • Use dictionaries when you need to store data as key-value pairs, rather than using a list or some other data structure.
  • Choose meaningful and descriptive keys for your dictionaries, as they will be used to access the values.
  • Use the get() method to access values in a dictionary, as it returns a default value if the key is not found, rather than raising a KeyError.
  • Use the update() method to merge two dictionaries, rather than trying to modify one dictionary in place.
  • Use the items(), keys(), and values() methods to iterate over the key-value pairs, keys, and values in a dictionary, respectively.