Open In App

Interesting Facts About Python Dictionary

Last Updated : 28 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python dictionaries are one of the most versatile and powerful built-in data structures in Python. They allow us to store and manage data in a key-value format, making them incredibly useful for handling a variety of tasks, from simple lookups to complex data manipulation. There are some interesting and lesser-known facts about Python dictionaries that make them such an essential tool in programming.

Here are Some Interesting Facts About Python Dictionaries

1. Dictionaries Are Ordered

Before Python 3.7, dictionaries did not preserve the order of insertion. However, with the introduction of Python 3.7 and beyond, dictionaries now maintain the order of the key-value pairs. Now we can rely on the insertion order of keys when iterating through dictionaries, which was previously a feature exclusive to OrderedDict.

Python
# Python 3.7 and later
d = {'a': 1, 'b': 2, 'c': 3}
print(d)  

Output
{'a': 1, 'b': 2, 'c': 3}

2. Dictionaries Can Have Any Immutable Type as Keys

The keys of a dictionary must be immutable, meaning they can be strings, numbers or tuples, but not lists or other mutable types. This feature ensures that the dictionary keys are hashable, maintaining the integrity and performance of lookups.

Python
d = {('x', 'y'): 100, 10: 'apple'}
print(d)  

Output
{('x', 'y'): 100, 10: 'apple'}

3. Dictionaries Are Hash-Based

Dictionaries in Python are implemented using hash tables, allowing for O(1) time complexity for lookups, inserts and deletions. This makes dictionaries extremely efficient when working with large datasets, as we can access data quickly based on the key.

4. Dictionaries Support Comprehensive Key Operations

Python dictionaries support a variety of useful operations for dealing with keys, including keys(), values() and items(). These methods allow us to efficiently iterate over the keys, values or key-value pairs, which is often needed for various tasks like data processing or aggregation.

Python
d = {'a': 1, 'b': 2}
print(d.keys())  
print(d.values()) 
print(d.items())  

Output
dict_keys(['a', 'b'])
dict_values([1, 2])
dict_items([('a', 1), ('b', 2)])

5. Dictionaries Support Destructive Operations

Python dictionaries support destructive operations like pop(), popitem() and del, which allow us to remove items from a dictionary efficiently. These methods make it easy to modify dictionaries in place, which is important when manipulating large data structures in applications like web development or data science.

Python
d = {'a': 1, 'b': 2}
print(d.pop('a'))  
print(d)           

Output
1
{'b': 2}

6. Dictionary Comprehensions

Just like list comprehensions, Python dictionaries support dictionary comprehensions, allowing us to create new dictionaries in a concise and readable way. It simplifies the creation of dictionaries based on existing data, making code more concise and readable.

Python
d = {x: x**2 for x in range(5)}
print(d) 

Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Dictionary Methods

Python dictionaries come with a variety of built-in methods that allow us to manipulate and interact with dictionary data. Here’s a list of few common and useful dictionary methods:

Functions Name

Descriptions

clear()

Removes all items from the dictionary

copy()

Returns a shallow copy of the dictionary

fromkeys()

Creates a dictionary from the given sequence

get()

Returns the value for the given key

items()

Return the list with all dictionary keys with values

keys()

Returns a view object that displays a list of all the keys in the dictionary in order of insertion

pop()

Returns and removes the element with the given key

popitem()

Returns and removes the item that was last inserted into the dictionary.

setdefault()

Returns the value of a key if the key is in the dictionary else inserts the key with a value to the dictionary

values()

Returns a view object containing all dictionary values, which can be accessed and iterated through efficiently

update()

Updates the dictionary with the elements from another dictionary or an iterable of key-value pairs. With this method, you can include new data or merge it with existing dictionary entries

These methods provide various functionalities for working with dictionaries in Python, making it easier to manage and manipulate data stored in key-value pairs.

Fun Features in Python Dictionaries

1. Dictionaries Can Have Non-String Keys

While strings are the most common type used as dictionary keys, dictionaries in Python can also use numbers, tuples and other immutable types as keys. This flexibility allows us to use different data types as identifiers in our data, making Python dictionaries more versatile.

Python
d = {42: 'GeeksForGeeks', (1, 2): 'coordinates'}
print(d[42])  

Output
GeeksForGeeks

2. The get() Method Helps Handle Missing Keys Gracefully

The get() method allows us to access the value of a key in a dictionary without raising a KeyError if the key does not exist. Instead, it returns a default value (which is None by default). It provides a way to handle missing keys gracefully without having to write additional error-handling code.

Python
d = {'a': 1, 'b': 2}
print(d.get('c', 'Key not found'))  

Output
Key not found

3. Mutable and Dynamic

Python dictionaries are mutable, meaning we can change them after they've been created. We can add, remove or update key-value pairs as needed. This dynamic nature allows us to build and modify dictionaries based on changing data, making them versatile for real-time applications.

Python
d = {'a': 1, 'b': 2}
d['c'] = 3  
d['a'] = 4 
del d['b']  
print(d) 

Output
{'a': 4, 'c': 3}

4. Any Data Type as Keys

Unlike some other languages, Python allows us to use any immutable data type (such as strings, numbers and tuples) as dictionary keys. This gives us flexibility in structuring our data. We can use complex types, like tuples, as keys to represent more structured or meaningful identifiers in our data.

Python
d = {(1, 2): 'tuple key', 3: 'integer key', 'name': 'string key'}
print(d[(1, 2)])  

Output
tuple key

Creating a Dictionary from two Lists

In Python, we can easily create a dictionary by using two lists: one for the keys and the other for the values. The idea is to pair each element from the first list (the keys) with an element from the second list (the values) to create key-value pairs in the dictionary.

Steps to Create a Dictionary:

  1. Have Two Lists: One list for keys and another list for values.
  2. Pair the Elements: Each item in the first list (the keys) will be paired with the corresponding item in the second list (the values).
  3. Create the Dictionary: We can use the zip() function to pair up the lists and then pass the result to the dict() constructor to create the dictionary.

Example:

Python
keys = ['a', 'b', 'c']
values = [1, 2, 3]

# Creating a dictionary from the two lists
d = dict(zip(keys, values))

print(d)

Output
{'a': 1, 'b': 2, 'c': 3}

Merging Dictionary

In Python, merging dictionaries means combining two or more dictionaries into one. If both dictionaries have the same key, the value from the second dictionary will overwrite the value from the first one. There are a few ways to merge dictionaries in Python.

Ways to Merge Dictionaries

1. Using the update() Method

The update() method adds key-value pairs from one dictionary into another. If a key already exists in the first dictionary, the value is updated with the value from the second dictionary.

Example:

Python
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}

d1.update(d2)

print(d1)

Output
{'a': 1, 'b': 3, 'c': 4}

2. Using the ** Unpacking Operator (Python 3.5+)

We can merge dictionaries by using the ** operator to unpack the key-value pairs and create a new dictionary.

Example:

Python
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}

d3 = {**d1, **d2}

print(d3)

Output
{'a': 1, 'b': 3, 'c': 4}

3. Using the | Operator (Python 3.9+)

In Python 3.9 and later, we can use the | operator to merge dictionaries.

Example:

Python
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}

d3 = d1 | d2

print(d3)

Output
{'a': 1, 'b': 3, 'c': 4}

Next Article

Similar Reads