我正在尝试使用 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
还有其他方法可以完成这个任务吗?
最佳答案
您需要迭代字典的值:
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']
是一个无效的操作,因为分别有一个string和int。请参阅documentation有关更多信息,请参阅词典。还有这个resource用于字典上的循环技术。
关于python - 从Python字典中提取id作为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65012989/