-2

I have two dictionaries:

dict_1 = ({'a':1, 'b':2,'c':3})
dict_2 = ({'x':4,'y':5,'z':6})

I want to take the keys from dict_1 and values from dict_2 and make a new dict_3

dict_3 = ({'a':4,'b':5,'c':6})
timgeb
  • 76,762
  • 20
  • 123
  • 145
mackrackit
  • 23
  • 3
  • 1
    There is absolutely no effort here on your part to show what you have tried. Please provide some code and explain what is not working out. More importantly, explain *exactly* what you are trying to do. – idjaw Mar 10 '16 at 23:26
  • 3
    I think you have the misconception that there is some predictable order to the dicts, a will not necessarily correspond to x etc.. – Padraic Cunningham Mar 10 '16 at 23:27
  • There's no logical pattern from dict_1 and dict_2 to dict_3. You are probably looking for .update, but you didn't write out your intention with dict_3 correctly. – AlanSE Mar 10 '16 at 23:27
  • 1
    Dicts are unordered, so there's no way to know which keys from dict1 to match to which values from dict2. – interjay Mar 10 '16 at 23:27
  • If you're trying to map keys alphabetically (for example a is the highest letter in dict1, and x is the highest in dict2), then you could, in principal, use `dict_1.keys()`, sort them, and then iterate. But like the others said, you didn't indicate any mapping for what you want, so it's hard to tell what you're asking – willwolfram18 Mar 10 '16 at 23:29

2 Answers2

4

What you are trying to do is impossible to do in any predictable way using regular dictionaries. As @PadraicCunningham and others have already pointed out in the comments, the order of dictionaries is arbitrary.

If you still want to get your result, you must use ordered dictionaries from the start.

>>> from collections import OrderedDict
>>> d1 = OrderedDict((('a',1), ('b',2), ('c', 3)))
>>> d2 = OrderedDict((('x',4), ('y',5), ('z', 6)))
>>> d3 = OrderedDict(zip(d1.keys(), d2.values()))
>>> d3
OrderedDict([('a', 4), ('b', 5), ('c', 6)])
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • Thank you for your solution. I did not realize it was an impossible task. I was trying to loop through the dictionaries and used the sorted command. – mackrackit Mar 11 '16 at 13:34
0

You can achieve this using zip and converting the resulting list to a dict:

dict(zip(dict_1.keys(), dict_2.values()))

But since the dictionaries are unordered, it won't be identical to your expected result:

{'a': 5, 'c': 4, 'b': 6}
Selcuk
  • 57,004
  • 12
  • 102
  • 110