How to construct a dictionary from two dictionaries in python?

python, python-2.7

Solution

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}

Problem

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} ```

Original source

Related problems