Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct a dictionary from two dictionaries in python? [duplicate]

Let's 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 constract a 3rd dictionary from the previous two:

z = {"y1":1,"x2":2,"x1":1,"y2":2}  
like image 1000
Mero Avatar asked Dec 04 '13 11:12

Mero


People also ask

Can there be duplicate in dictionary Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can we merge two dictionaries in Python?

Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

Can dictionary have duplicate items?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.


Video Answer


2 Answers

If you want 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 the 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

Output

{'y1': 1, 'x2': 2, 'x1': 1, 'y2': 2}
like image 67
Kobi K Avatar answered Oct 07 '22 14:10

Kobi K


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

z = x.copy()
z.update(y)
like image 7
jonrsharpe Avatar answered Oct 07 '22 13:10

jonrsharpe