【问题标题】:Convert list of nested dictionary into dictionary in Python将嵌套字典列表转换为Python中的字典
【发布时间】:2019-12-13 01:25:28
【问题描述】:

我有一个嵌套字典列表,如下所示。字典里面也有列表。我不想更改内部列表,而是将整个列表变成字典。名单如下:

[{"id" : "A", "data" : [{"key_1" : 012},{"key_2" : 123}, {"key_3" : 234}]}]

我只想将列表本身更改为字典而不更改内部列表,如下所示:

{{"id" : "A", "data" : [{"key_1" : 012},{"key_2" : 123}, {"key_3" : 234}]}}

感谢您在这方面的帮助。

【问题讨论】:

  • 预期结果无效。
  • ggorlen 是正确的,您需要在字典中有一个键:值对。最接近我认为你想要的是(顶部列表称为'a'): new_dict={'keyname':a[0]}
  • 谢谢@jhso。我修改了列表以显示层次结构。最初列表a[{'Emp_id': 'A', 'Gender': 'M', 'Age': 32, 'Result': [{'Month': 'Aug', 'Incentive': 3000}, {'Month': 'Sep', 'Incentive': 3500}, {'Month': 'Oct', 'Incentive': 2000}]}, {'Emp_id': 'B', 'Gender': 'M', 'Age': 35, 'Result': [{'Month': 'Aug', 'Incentive': 1500}]}, {'Emp_id': 'C', 'Gender': 'F', 'Age': 31, 'Result': [{'Month': 'Aug', 'Incentive': 5000}, {'Month': 'Sep', 'Incentive': 2400}]}]。通过应用new_dict={'keyname':a[0]},new_dict 只保留"Emp_id" : "A"。我怎样才能保留所有内容?
  • 您应该格式化输入和预期输出,使结构清晰。
  • 抱歉,不知道您的列表中有多个字典。您可以执行 new_dict={'keyname':a},也可以执行 dict 理解,即。 new_dict={i['Emp_id']:i for i in a}

标签: json python-3.x dictionary


【解决方案1】:

使用字典理解和zip 字典列表以及您想要的任何键列表。下面是一个使用 ascii 小写字母子集的示例:

{ pair[0]: pair[1] for pair in list(zip([*string.ascii_lowercase[0:len(input)]], input))}
>>> foo = [   {   'Age': 32,
        'Emp_id': 'A',
        'Gender': 'M',
        'Result': [   {'Incentive': 3000, 'Month': 'Aug'},
                      {'Incentive': 3500, 'Month': 'Sep'},
                      {'Incentive': 2000, 'Month': 'Oct'}]},
    {   'Age': 35,
        'Emp_id': 'B',
        'Gender': 'M',
        'Result': [{'Incentive': 1500, 'Month': 'Aug'}]},
    {   'Age': 31,
        'Emp_id': 'C',
        'Gender': 'F',
        'Result': [   {'Incentive': 5000, 'Month': 'Aug'},
                      {'Incentive': 2400, 'Month': 'Sep'}]}]


>>> { pair[0]: pair[1] for pair in list(zip([*string.ascii_lowercase[0:len(input)]], input))}


>>> {   'a': {   'Age': 32,
             'Emp_id': 'A',
             'Gender': 'M',
             'Result': [   {'Incentive': 3000, 'Month': 'Aug'},
                           {'Incentive': 3500, 'Month': 'Sep'},
                           {'Incentive': 2000, 'Month': 'Oct'}]},
    'b': {   'Age': 35,
             'Emp_id': 'B',
             'Gender': 'M',
             'Result': [{'Incentive': 1500, 'Month': 'Aug'}]},
    'c': {   'Age': 31,
             'Emp_id': 'C',
             'Gender': 'F',
             'Result': [   {'Incentive': 5000, 'Month': 'Aug'},
                           {'Incentive': 2400, 'Month': 'Sep'}]}}

注意:您可以如下打印代码:

import pp = pprint.PrettyPrinter(indent=4)
pp.pprint(data)

【讨论】:

    猜你喜欢
    • 2022-12-05
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 2020-05-16
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多