【问题标题】:Converting Array of Python dictionaries to Python dictionary using comprehensions使用推导将 Python 字典数组转换为 Python 字典
【发布时间】:2018-05-02 16:32:48
【问题描述】:

我有一个 Python 字典数组,如下所示:

[
 {
  "pins": [1,2],
  "group": "group1"
 },
 {
  "pins": [3,4],
  "group": "group2"
 }
]

我想把这个字典数组转换成下面的字典:

{ 1: "group1", 2: "group1", 3: "group2", 4: "group2" }

我编写了以下双 for 循环来完成此操作,但很好奇是否有更有效的方法来执行此操作(也许是一种理解?):

new_dict = {}
for d in my_array:
    for pin in d['pins']:
        new_dict[pin] = d['group']

【问题讨论】:

    标签: python dictionary dictionary-comprehension


    【解决方案1】:

    让我们试试字典理解:

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

    【讨论】:

      猜你喜欢
      • 2017-07-21
      • 2013-02-19
      • 2016-10-16
      • 1970-01-01
      • 2018-05-04
      • 2014-02-19
      • 1970-01-01
      相关资源
      最近更新 更多