使用理解将Python字典数组转换为Python字典

时间:2018-05-02 16:32:49

标签: python dictionary dictionary-comprehension

我有一个字典的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']

1 个答案:

答案 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'}