首页 > 解决方案 > 从python字典中提取id作为列表

问题描述

我正在尝试使用 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

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

标签: pythonlistdictionarynested

解决方案


您需要遍历字典的值:

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。有关更多信息,请参阅字典文档。这也是在字典上循环技术的资源


推荐阅读