英文:
get all keys from nested json file (python)
问题
以下是翻译好的部分:
"Im tr"
{
"results": [{
"firstName": "Emma",
"href": "https://192.168.1.198:8904/api/cardholders/569",
"id": "569",
"lastName": "Bennett"
}, {
"authorised": true,
"firstName": "Dory",
"id": "570",
"lastName": "mcKormick"
}]
}
最后,我想要一个包含所有现有键的列表:authorised, firstName, href, id, lastName
我只是不能通过迭代和使用 .key() 方法来获得它。 有人有建议吗?
英文:
Im tr
{
"results": [{
"firstName": "Emma",
"href": "https://192.168.1.198:8904/api/cardholders/569",
"id": "569",
"lastName": "Bennett"
} {
"authorised": true,
"firstName": "Dory",
"id": "570",
"lastName": "mcKormick"
}]
In the end i want a list with all keys present: authorised, firstName, href, id, lastName
i just do not seem to get it trought iterations, using the .key() method. Anyone has a suggestion?
答案1
得分: 1
Use a set
to prevent duplicates. Then loop through all the dictionaries, adding the keys to the set.
data = {
"results": [{
"firstName": "Emma",
"href": "https://192.168.1.198:8904/api/cardholders/569",
"id": "569",
"lastName": "Bennett"
}, {
"authorised": True,
"firstName": "Dory",
"id": "570",
"lastName": "mcKormick"
}]
}
keys = set()
for d in data['results']:
keys |= d.keys()
print(keys)
# Output: {'authorised', 'firstName', 'lastName', 'href', 'id'}
This assumes there's just one list of dictionaries, not arbitrary nesting depth. For the latter you'll need to write a recursive function.
英文:
Use a set
to prevent duplicates. Then loop through all the dictionaries, adding the keys to the set.
data = {
"results": [{
"firstName": "Emma",
"href": "https://192.168.1.198:8904/api/cardholders/569",
"id": "569",
"lastName": "Bennett"
}, {
"authorised": True,
"firstName": "Dory",
"id": "570",
"lastName": "mcKormick"
}]
}
keys = set()
for d in data['results']:
keys |= d.keys()
print(keys)
# Output: {'authorised', 'firstName', 'lastName', 'href', 'id'}
This assumes there's just one list of dictionaries, not arbitrary nesting depth. For the latter you'll need to write a recursive function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论