Python Dictionaries

  • Read
  • Discuss


Python dictionaries, also known as associative arrays or hash maps, are a built-in data structure that stores a collection of key-value pairs. They are similar to lists, but instead of using integer indices to access elements, you use keys, which can be any immutable type (strings, numbers, etc.). 

Following are properties of Python dictionaries:

  • Unordered: Dict does not maintain the order of data insertion
  • Mutable: We can modify dict key/values items
  • Heterogeneous: Dict can contain different types of data
  • Unique: Keys should be unique in dictionaries

Types of Data That Can Be Stored in Python Dictionaries

In Python, dictionaries can store a collection of key-value pairs where the keys and values can be of any data type. However, the keys must be immutable, which means that they cannot be changed once they are created. This means that types such as lists or dictionaries cannot be used as keys, but strings, numbers, tuples (as long as they contain only immutable types) can be used as keys.

Here are some examples of different types of data that can be stored in a Python dictionary:

  1. Strings as keys and values:
my_dict = {'name': 'John', 'age': 30, 'gender': 'male'}
  1. Numbers as keys and values:
my_dict = {1: 'one', 2: 'two', 3: 'three'}
  1. Tuples as keys and lists as values:
my_dict = {(1, 2): ['apple', 'orange'], (3, 4): ['banana', 'pear']}
  1. Nested dictionaries as values:
my_dict = {'person1': {'name': 'John', 'age': 30, 'gender': 'male'},
            'person2': {'name': 'Mary', 'age': 25, 'gender': 'female'}}
  1. Mixing different types:
my_dict = {'name': 'John', 'age': 30, 'gender': 'male', 1: ['apple', 'orange'], 2: {'color': 'red'}}

It’s important to keep in mind that the keys of a dictionary must be unique if you add a key-value pair with a key that already exists in the dictionary, the value for that key will be updated to the new value. The keys in the dictionaries must be immutable and unique, making them highly suitable for various data structures that need quick value retrieval based on the keys.

Dictionaries built-in functions table

Python has several built-in functions for working with dictionaries. Here are a few most commonly used ones:

d = dict()Creates a new dictionary
len(d)Returns the number of items in the dictionary
d.clear()Removes all items from the dictionary
d.copy()Returns a shallow copy of the dictionary
d.fromkeys(seq[, v])Returns a new dictionary with keys from seq and value v
d.get(key[, default])Returns the value of the key, or default if the key is not in the dictionary
d.items()Returns a view object of the dictionary’s items
d.keys()Returns a view object of the dictionary’s keys
d.pop(key[, default])Removes a key from the dictionary and returns its value, or default if a key is not in the dictionary
d.popitem()Removes and returns an arbitrary item (key, value) from the dictionary
d.update(other)Adds key-value pairs from other to d. If a key is in d and in other, the value from other is used
d.values()Returns a view object of the dictionary’s values

Implement Python Dictionaries

Here’s an example of how to create and use a dictionary:

Creating a dictionary

my_dict = {'apple': 0.5, 'banana': 0.25, 'orange': 0.75}

Accessing an element

print(my_dict['apple']) # Output: 0.5

Adding an element

my_dict['pear'] = 0.3
print(my_dict) # Output: {'apple': 0.5, 'banana': 0.25, 'orange': 0.75, 'pear': 0.3}

Modifying an element

my_dict['apple'] = 0.6
print(my_dict) # Output: {'apple': 0.6, 'banana': 0.25, 'orange': 0.75, 'pear': 0.3}

Removing an element

del my_dict['pear']
print(my_dict) # Output: {'apple': 0.6, 'banana': 0.25, 'orange': 0.75}

You can also access the keys and values separately using the keys() and values() methods:

Accessing keys

print(my_dict.keys()) # Output: dict_keys(['apple', 'banana', 'orange'])

 Accessing values

print(my_dict.values()) # Output: dict_values([0.6, 0.25, 0.75])

Dictionaries also have a items() method that returns a list of tuples, each containing a key-value pair:

print(my_dict.items()) # Output: dict_items([('apple', 0.6), ('banana', 0.25), ('orange', 0.75)])

You can use the in keyword to check if a key is in a dictionary:

print('apple' in my_dict) # Output: True
print('pear' in my_dict) # Output: False

Dictionaries also have a get() method that allows you to retrieve the value of a key, but it also allows you to specify a default value to return if the key is not found in the dictionary.

print(my_dict.get('apple')) # Output: 0.6
print(my_dict.get('pear', 0)) # Output: 0

Dictionaries are unordered, which means they don’t maintain any order among the elements, they are mutable and fast. And they are widely used in various data structures, like JSON objects.

Dictionaries are also commonly used with loops to perform operations on each key-value pair. For example, you can use a for loop to print all the keys and values in a dictionary like this:

print(my_dict.get('apple')) # Output: 0.6
print(my_dict.get('pear', 0)) # Output: 0

Use Cases of Python dictionaries

Python dictionaries are very versatile and have a wide range of use cases. Here are a few examples of how they can be used:

  1. Storing key-value pairs: Dictionaries are commonly used to store key-value pairs, where the keys are unique strings or numbers and the values can be of any data type. For example, you could use a dictionary to store the prices of different products, with the product names as the keys and the prices as the values.
  2. Representing data: Dictionaries can represent complex data structures in a more human-readable format. For example, you could use a dictionary to represent a JSON object, where the keys are the field names and the values are the field values.
  3. Counting occurrences: Dictionaries can be used to count the occurrences of items in a list. For example, you could use a dictionary to count the number of times each word appears in a text.
  4. Grouping data: Dictionaries can be used to group data based on certain criteria. For example, you could use a dictionary to group a list of people by their age.
  5. Lookup tables: Dictionaries can be used as efficient lookup tables, where the keys map to specific values. This is useful when you have a large amount of data and need to perform many lookups on it.
  6. Implementation of Graphs: With the help of dictionaries, Graphs can be implemented in python. Where in the dictionary keys can be considered nodes and values can be considered edges.

These are just a few examples of the many use cases of python dictionaries, they are very flexible and can be used in a wide variety of ways.

Limitations of Python dictionaries

While Python dictionaries are a very powerful and versatile data structure, they have some limitations. Here are a few examples:

  1. Unordered: Dictionaries in Python are unordered, which means that the items are stored in no particular order.
  2. Immutable keys: The keys in a Python dictionary must be immutable, meaning they cannot be modified after they have been added to the dictionary. 
  3. No support arithmetic operation: Dictionaries do not support arithmetic operations, such as addition or multiplication, as they are intended to store key-value pairs and not numerical data.
  4. Concurrency and Multi-threading: Dictionaries are not thread-safe, which means that if multiple threads try to access or modify a dictionary simultaneously, it can lead to race conditions and unexpected behaviour.

However, most of these limitations can be addressed with the use of other python data structures such as orderedDict, defaultDict, etc, and using some other libraries for concurrent programming.

Leave a Reply

Leave a Reply

Scroll to Top