使用理解将 Python 字典数组转换为 Python 字典
Converting Array of Python dictionaries to Python dictionary using comprehensions
我有一个 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']
让我们试试字典理解:
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'}
我有一个 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']
让我们试试字典理解:
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'}