【问题标题】:Python list comprehension for list of dictd into a list of tuple with a subset of dict key-value pairsPython列表理解将dictd列表转换为具有dict键值对子集的元组列表
【发布时间】:2020-08-28 01:26:40
【问题描述】:

我想使用列表推导将上述内容转换为元组列表,但元组中只有每个字典的一个子集。

来源

source = [
  {'gem': 'gold', 'dimensions': {"weight":120, "height":0, "color":240}, 'shine': '90', 'worth': 10000}, 
  {'gem': 'diamond', 'dimensions': {"weight":80, "height":20, "color":10}, 'shine': '190', 'worth': 5000}
  ...
]

根据上面的来源,完成后列表应如下所示:

[(120, 240),(80, 10) ]

列表中的每个元组都基于 Source 中匹配索引处的 dict,但只有嵌套 dict 的一部分被选择包含在类型中:

所需的数据集

[(dimensions.weight, dimensions.color), ...]

我尝试了几种不同的方法,但没有比这更进一步:

[g["dimensions"] for g in source]

产生

[{"weight":120, "height":0, "color":240}, {"weight":80, "height":20, "color":10}]

【问题讨论】:

    标签: python list dictionary list-comprehension


    【解决方案1】:

    你很接近,只需要指定要包含在元组中的值

    [(g["dimensions"]["weight"], g["dimensions"]["color"]) for g in source]
    

    【讨论】:

    • 当然没问题:)
    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 2018-05-28
    • 2017-07-04
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多