Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create Python dictionary from the value of another dictionary?
You can create a new Python dictionary by combining values from other dictionaries using several methods. Python provides multiple approaches to merge dictionaries, each suitable for different scenarios and Python versions.
Using Dictionary Unpacking (Python 3.5+)
The ** operator unpacks dictionaries and combines them into a new dictionary ?
a = {'foo': 125}
b = {'bar': "hello"}
c = {**a, **b}
print(c)
{'foo': 125, 'bar': 'hello'}
Using dict() Constructor
For older Python versions, you can use the dict() constructor with unpacking ?
a = {'foo': 125}
b = {'bar': "hello"}
c = dict(a, **b)
print(c)
{'foo': 125, 'bar': 'hello'}
Using copy() and update() Methods
This approach creates a copy of the first dictionary and updates it with the second ?
def merge_dicts(x, y):
z = x.copy() # start with x's keys and values
z.update(y) # modify z with y's keys and values
return z
a = {'foo': 125}
b = {'bar': "hello"}
c = merge_dicts(a, b)
print(c)
{'foo': 125, 'bar': 'hello'}
Using Union Operator (Python 3.9+)
Python 3.9 introduced the | operator for dictionary merging ?
a = {'foo': 125}
b = {'bar': "hello"}
c = a | b
print(c)
{'foo': 125, 'bar': 'hello'}
Comparison
| Method | Python Version | Best For |
|---|---|---|
{**a, **b} |
3.5+ | Most readable and common |
dict(a, **b) |
All versions | Older Python versions |
copy() + update() |
All versions | Complex merging logic |
a | b |
3.9+ | Clean syntax in modern Python |
Conclusion
Use dictionary unpacking {**a, **b} for most cases in Python 3.5+. For newer versions, the union operator | provides clean syntax. Use copy() + update() for complex merging scenarios.
