Skip to content Skip to sidebar Skip to footer

Build A New Dictionary From The Keys Of One Dictionary And The Values Of Another Dictionary

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 = (

Solution 1:

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)])

Solution 2:

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}

Post a Comment for "Build A New Dictionary From The Keys Of One Dictionary And The Values Of Another Dictionary"