How to build a dictionary from two dictionaries in python?

Say I have a dictionary:

x = {"x1":1,"x2":2,"x3":3} 

and I have another dictionary:

 y = {"y1":1,"y2":2,"y3":3} 

Is there any neat way to build a third dictionary from the two previous ones:

 z = {"y1":1,"x2":2,"x1":1,"y2":2} 
+8
python
source share
3 answers

If you need the whole 2 dicts:

 x = {"x1":1,"x2":2,"x3":3} y = {"y1":1,"y2":2,"y3":3} z = dict(x.items() + y.items()) print z 

Output:

 {'y2': 2, 'y1': 1, 'x2': 2, 'x3': 3, 'y3': 3, 'x1': 1} 

If you want a partial dict:

 x = {"x1":1,"x2":2,"x3":3} y = {"y1":1,"y2":2,"y3":3} keysList = ["x2", "x1", "y1", "y2"] z = {} for key, value in dict(x.items() + y.items()).iteritems(): if key in keysList: z.update({key: value}) print z 

Exit

 {'y1': 1, 'x2': 2, 'x1': 1, 'y2': 2} 
+5
source share

You can use copy for x , then update to add the keys and values ​​from y :

 z = x.copy() z.update(y) 
+3
source share

Try something like this:

 dict([(key, d[key]) for d in [x,y] for key in d.keys() if key not in ['x3', 'y3']]) {'x2': 2, 'y1': 1, 'x1': 1, 'y2': 2} 
0
source share

All Articles