
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Python Dictionary from Another Dictionary's Value
You can do this by merging the other dictionary to the first dictionary. In Python 3.5+, you can use the ** operator to unpack a dictionary and combine multiple dictionaries using the following syntax −
Syntax
a = {'foo': 125} b = {'bar': "hello"} c = {**a, **b} print(c)
Output
This will give the output −
{'foo': 125, 'bar': 'hello'}
This is not supported in older versions. You can however replace it using the following similar syntax −
Syntax
a = {'foo': 125} b = {'bar': "hello"} c = dict(a, **b) print(c)
Output
This will give the output −
{'foo': 125, 'bar': 'hello'}
Another thing you can do is using copy and update functions to merge the dictionaries.
example
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)
Output
This will give the output −
{'foo': 125, 'bar': 'hello'}
Advertisements