【问题标题】:splitting nested dictionaries in python在python中拆分嵌套字典
【发布时间】:2018-10-04 02:00:36
【问题描述】:

我有一件简单的事情,但由于某种原因,我的思维现在被阻塞了 这种数据叫什么名字

[{'self': 'test', 'id': 4, 'name': 'IT Network Support'}, {'self': 'tes_1', 'id': 5, 'name': 'IT PC Support'}]

如何将它们分成 2 个字典

它也可以是动态的并更改为

[{'self': 'test', 'id': 4, 'name': 'IT Network Support'}, {'self': 'tes_1', 'id': 5, 'name': 'IT PC Support'} ,{'self': 'tes_2', 'id': 6, 'name': 'IT Voice Support'} ]

我想要一个动态的解决方案

【问题讨论】:

标签: python dictionary


【解决方案1】:

最简单的方法是:

dict1, dict2 = [{'self': 'test', 'id': 4, 'name': 'IT Network Support'}, {'self': 'tes_1', 'id': 5, 'name': 'IT PC Support'}]

将它们解包到变量 dict1 和 dict2 中

您也可以直接索引到列表中,例如

dict_list = [{'self': 'test', 'id': 4, 'name': 'IT Network Support'}, {'self': 'tes_1', 'id': 5, 'name': 'IT PC Support'}]
dict1 = dict_list[0]
dict2 = dict_list[1]

【讨论】:

    【解决方案2】:

    你可以在 python 中解压迭代器!

    a, b = [{'self': 'test', 'id': 4, 'name': 'IT Network Support'}, {'self': 'tes_1', 'id': 5, 'name': 'IT PC Support'}]

    【讨论】:

    • 如果2个字典变成3个怎么办?
    • 在 python3 中,您可以像 a, *b = [1, 2, 3] 一样解压缩,其他所有内容都进入 b,但否则我会说使用 for 循环并在一次性变量 @987654324 中执行您需要的任何操作@
    猜你喜欢
    • 2017-08-31
    • 1970-01-01
    • 2021-12-09
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 2014-09-13
    • 2011-12-25
    相关资源
    最近更新 更多