我有一个字典的Python数组,如下所示:
[
{
"pins": [1,2],
"group": "group1"
},
{
"pins": [3,4],
"group": "group2"
}
]
我想将这个字典数组转换为以下字典:
{ 1: "group1", 2: "group1", 3: "group2", 4: "group2" }
我写了下面的双循环来完成这个,但是如果有一个更有效的方法来做这个(可能是一个理解?)很好奇:)
new_dict = {}
for d in my_array:
for pin in d['pins']:
new_dict[pin] = d['group']
答案 0 :(得分:3)
让我们尝试字典理解:
new_dict = {
k : arr['group'] for arr in my_array for k in arr['pins']
}
这相当于:
new_dict = {}
for arr in my_array:
for k in arr['pins']:
new_dict[k] = arr['group']
print(new_dict)
{1: 'group1', 2: 'group1', 3: 'group2', 4: 'group2'}