Search code examples
pythondictionaryordereddictionary

How to change keys of ordered dict to that of keys from other ordered dict in Python?


I have two ordered dicts D1 and D2. I want to assign key names of D2 to D1 (overwrite existing key names of D1). How to do that?

Example:

D1 = {'first_key': 10, 'second_key': 20}
D2 = {'first_new_key': 123, 'second_new_key': 456}

Now I want to assign key names of D2 to D1 so that D1 becomes

{'first_new_key': 10, 'second_new_key': 20}

Solution

  • here's a solution:

    keys = D2.keys()
    values = D1.values()
    new_dict = dict(zip(keys, values))
    

    If your'e into 1-liners (that's why we have python, right?):

    new_dict = dict(zip(D2.keys(), D1.values()))
    

    As mentioned in the comments, the insertion order between the 2 dictionaries must match.

    EDIT

    I figured out that you want to overwrite D1. In that case you can simply do:

    D1 = dict(zip(D2.keys(), D1.values()))
    

    EDIT 2

    As Barmar mentioned in another answer, in order to have ordered dictionaries, one must use collections.OrderedDict().