使用理解将Python字典数组转换为Python字典
我有一个Python字典数组,如下所示:使用理解将Python字典数组转换为Python字典,python,dictionary,dictionary-comprehension,Python,Dictionary,Dictionary Comprehension,我有一个Python字典数组,如下所示: [ { "pins": [1,2], "group": "group1" }, { "pins": [3,4], "group": "group2" } ] 我想将此字典数组转换为以下字典: { 1: "group1", 2: "group1", 3: "group2", 4: "group2" } 我写了下面的double for循环来实现这一点,但我很好奇是否有更有效的方法来实现这一点(也许是一种理解?): 让我们试试字典
[
{
"pins": [1,2],
"group": "group1"
},
{
"pins": [3,4],
"group": "group2"
}
]
我想将此字典数组转换为以下字典:
{ 1: "group1", 2: "group1", 3: "group2", 4: "group2" }
我写了下面的double for循环来实现这一点,但我很好奇是否有更有效的方法来实现这一点(也许是一种理解?):
让我们试试字典理解:
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']
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'}