【问题标题】:How to append a list of dictionaries to the value of a key in a dictionary?如何将字典列表附加到字典中键的值?
【发布时间】:2020-04-09 02:28:06
【问题描述】:

例如:

list1 = [{'vehicle': {'bmw': 2, 'cus': 'mr x', 'extra': 'he is awesome'}}, 
        {'fruit': {'mango': 2, 'color': 'gelb', 'extra': 'king of fruits'}}]

print(list1)

[{'vehicle': {'bmw': 2, 'cus': 'mr x', 'extra': '他真棒'}},
{'fruit': {'mango': 2, 'color': 'gelb', 'extra': '水果之王'}}]

final_ds_dict={}

final_ds_dict.update({'datasets': {'training': list1}})

print(final_ds_dict)

我得到的输出如下:

{'datasets': {'training': [{'vehicle': {'bmw': 2,
     'cus': 'mr x',
     'extra': 'he is awesome'}},
   {'fruit': {'mango': 2, 'color': 'gelb', 'extra': 'king of fruits'}}]}}

但是,我不会将其附加为列表。

所需的输出应如下所示:

{'datasets': {'training': {'vehicle': {'bmw': 2,
     'cus': 'mr x',
     'extra': 'he is awesome'}},
   {'fruit': {'mango': 2, 'color': 'gelb', 'extra': 'king of fruits'}}}}

有人可以帮忙解决这个问题吗?

【问题讨论】:

  • 您想要的输出不是有效的 python 字典。也许你在水果之前有一个额外的{

标签: python list python-2.7 ordereddictionary dictionary-comprehension


【解决方案1】:

您可以使用dict 的列表推导来形成内部字典:

list1 = [{'vehicle': {'bmw': 2, 'cus': 'mr x', 'extra': 'he is awesome'}}, 
    {'fruit': {'mango': 2, 'color': 'gelb', 'extra': 'king of fruits'}}]
result = {'datasets':dict(i for b in list1 for i in b.items())}

输出:

{'datasets': 
    {'vehicle': {'bmw': 2, 'cus': 'mr x', 'extra': 'he is awesome'}, 
     'fruit': {'mango': 2, 'color': 'gelb', 'extra': 'king of fruits'}
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 2020-12-06
    • 1970-01-01
    • 2022-12-17
    • 2015-07-03
    • 2017-11-15
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多