【问题标题】:Combine a dictionary item to a list of dictionaries in将字典项与字典列表结合
【发布时间】:2020-03-23 23:46:35
【问题描述】:

希望你有一个美好的时刻,

我的字典有问题。

假设我们有一个字典 An 键(在这种情况下,有 2 个):

A = {
    weather: ['sunny', 'rain', 'cloudy'],   
    temperature: ['warm', 'cold']
}

我们希望为每个项目组合创建一个 listdict。由于在示例中有 3 项 x 2 项,因此将有一个包含 6 个字典的列表。

结果将如下所示:

B = [
    {weather: 'sunny', temperature='warm'},
    {weather: 'sunny', temperature='cold'},
    {weather: 'rain', temperature='warm'},
    {weather: 'rain', temperature='cold'},
    {weather: 'cloudy', temperature='warm'},
    {weather: 'cloudy', temperature='cold'}
    ]

我目前尝试的是:

B = []
for key,value  in A.items():
    for item in value:
        B.append([key, item])

但它失败了。

有没有办法做到这一点? 以下是一些重要的问题:

任何解决方案将不胜感激。 (对不起我的英语不好)。

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    有一个使用zipvalues 方法和itertools.product 的简短表达式:

    >>> from itertools import product
    >>> A = {'weather': ['sunny', 'rain', 'cloudy'], 'temperature': ['warm', 'cold']}
    >>> B = [dict(zip(A, x)) for x in product(*A.values())]
    >>> for d in B:
    ...   print(d)
    ...
    {'weather': 'sunny', 'temperature': 'warm'}
    {'weather': 'sunny', 'temperature': 'cold'}
    {'weather': 'rain', 'temperature': 'warm'}
    {'weather': 'rain', 'temperature': 'cold'}
    {'weather': 'cloudy', 'temperature': 'warm'}
    {'weather': 'cloudy', 'temperature': 'cold'}
    

    product 的调用会创建一个像('sunny', 'warm') 这样的对列表。当您使用 dict 键压缩这样的一对时,您会得到一系列像 ('weather','sunny')('temperature','warm') 这样的对,dict 可以将其转换为所需的字典。

    请注意,这是可行的,因为提供键的迭代器和 values 方法都以相同的顺序返回它们的元素,因此您不必担心会得到类似 {'weather': 'warm', 'temperature': 'sunny'} 的东西。

    【讨论】:

    • 嘿,谢谢你。这就是我的意思。最后可以生成笛卡尔积。干杯!
    【解决方案2】:
    A = {
        'weather': ['sunny', 'rain', 'cloudy'],   
        'temperature': ['warm', 'cold']
    }
    
    B = [{'weather': a,'temperature': b} for a in A['weather'] for b in A['temperature']]
    
    

    你能试试这个吗!

    【讨论】:

    • 非常感谢,但它会为每个键静态创建一个 for 循环。
    猜你喜欢
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    相关资源
    最近更新 更多