简体   繁体   中英

Pythonic way of switching nested dictionary keys with nested values

In short I'm working with a nested dictionary structured like this:

nested_dict = {'key1':{'nestedkey1': 'nestedvalue1'}}

I'm trying to find a pythonic way of switching the keys with the nested values, so it would look like this:

nested_dict = {'nestedvalue1':{'nestedkey1': 'key1'}}

I'm also trying to rename the nested key values, so ultimately the dictionary would look like this:

nested_dict = {'nestedvalue1':{'NEWnestedkey1': 'key1'}}

This is closer to what I'm working with:

original_dict = {
    'buford': {'id': 1},
    'henley': {'id': 2},
    'emi': {'id': 3},
    'bronc': {'id': 4}
}

I want it to look like this:

new_dict = {
    1: {'pet': 'buford'},
    2: {'pet': 'henley'},
    3: {'pet': 'emi'},
    4: {'pet': 'bronc'}
}

Is there a way to do this in one line using a dictionary comprehension? I'm trying to get the very basics here and avoid having to use things like itertools.

You can use a dictionary comprehension to achieve this, 'swapping' things round as you build it:

new_dict = {v['id']: {'pet': k} for k, v in original_dict.items()}

To expand it to a for loop, it'd look something like:

new_dict = {}
for k, v in original_dict.items():
  new_dict[v['id']] = {'pet': k}

Note that both cases obviously rely on the 'id' value being unique, or the key will be overwritten for each occurrence.

For a more generic solution, you can try this:

def replace(d, change_to = 'pet'):
  return {b.values()[0]:{change_to:a} for a, b in d.items()}

Output:

{1: {'pet': 'buford'}, 2: {'pet': 'henley'}, 3: {'pet': 'emi'}, 4: {'pet': 'bronc'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM