【问题标题】:Extract id's as a list from python dictionary从python字典中提取id作为列表
【发布时间】:2021-03-08 19:10:52
【问题描述】:

我正在尝试使用 python 从嵌套字典中提取 id, 但是,当我运行下一个代码时它会运行错误:

nested_dictionary = {
    "name": "field",
    "vacant": "capable",
    "employees": 
        {
            1: {"id": 1, "name": "Joe", "px": "px1"},
            2: {"id": 2, "name": "Mary", "px": "px2"},
            3: {"id": 3, "name": "George", "px": "px3"},
            4: {"id": 4, "name": "Louise", "px": "px4"},
            5: {"id": 5, "name": "Malcolm", "px": "px5"},
            6: {"id": 6, "name": "Reese", "px": "px6"},
        },
        "columns": 
        [
            "col1",
            "col2",
            "col3",
            "col4"
       
        ],
    "columns_2": 
        [
            "col5",
            "col6",
            "col7"
        ]
}


for p in nested_dictionary['employees']
    print('id:' + p['id'])

控制台输出:

Type Error: i object is not subscriptable

预期输出:

id: 1
id: 2
id: 3
id: 4
id: 5
id: 6

还有其他方法可以完成这项任务吗?

【问题讨论】:

  • print('id:' + str(nested_dictionary['employees'][p]['id'])),每个p代表每个员工的key

标签: python list dictionary nested


【解决方案1】:

您需要遍历字典的值:

for p in nested_dictionary['employees'].values():
    print(f'id: {p["id"]}')

输出

id: 1
id: 2
id: 3
id: 4
id: 5
id: 6

目前您正在迭代键。另请注意:

'id:' + p['id']

是一个无效操作,因为分别有一个 stringint。有关详细信息,请参阅字典上的 documentation。还有这个resource 用于在字典上循环技术。

【讨论】:

    猜你喜欢
    • 2018-11-04
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2022-07-12
    • 2017-12-15
    • 2020-12-12
    • 1970-01-01
    • 2022-11-21
    相关资源
    最近更新 更多