[英]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: 我试图找到一种用嵌套值切换键的pythonic方法,所以它看起来像这样:
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. 我试图在这里得到基础知识,避免使用像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: 要将它扩展为for循环,它看起来像:
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. 请注意,这两种情况显然都依赖于'id'
值是唯一的,或者每次出现都会覆盖密钥。
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'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.