30

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}  
4
  • 1
    What happened to x3 and y3?
    – Alfe
    Commented Dec 4, 2013 at 11:43
  • Sorry, I might didn't explain very well. I don't want to add the whole two dictionaries to make new one. I just want some keys from the first one and some other keys from the second one then create a new dictionary
    – Mero
    Commented Dec 4, 2013 at 11:50
  • @user2468276 I've updated my answer with what you wanted.
    – Kobi K
    Commented Dec 4, 2013 at 12:01
  • 1
    x = { **x, **y }
    – pradeexsu
    Commented Oct 16, 2020 at 17:45

3 Answers 3

9

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}
2
  • 1
    First solution will work in python2, but not in python3 Commented Mar 3, 2016 at 9:35
  • @JpuntoMarcos You are right (an old answer), You can use z = dict(list(x.items()) + list(y.items())) for python3 but keep in mind it's more expensive.
    – Kobi K
    Commented Mar 3, 2016 at 12:32
7

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

z = x.copy()
z.update(y)
2

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}

Not the answer you're looking for? Browse other questions tagged or ask your own question.