获取嵌套的JSON文件中的所有键(Python)。

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月1日 06:23:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定