How to create Python dictionary from the value of another dictionary?

PythonProgramming

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'}
raja
Published on 18-Apr-2018 13:02:15
Advertisements