将JSON列表转换为字典

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

Converting JSON list to dictionary

问题

以下是已翻译的内容:

我正在使用 python 并且有以下存储为列表的 JSON 块,名为 json_player

[
    {
        "id": "name",
        "value": "john"
    },
    {
        "id": "sport",
        "value": "baseball"
    },
    {
        "id": "age",
        "value": "20"
    }
]

请注意,这是从以下代码生成的结果:

json_object = json.loads(df['customFields'])
json_player = json_object['player']

我知道我可以使用以下代码访问 json_player 中的单个字符串:

json_player[0]['value']

这将返回字符串 john

但是,我想要能够按名称而不是索引调用单个键值对,以便在底层 JSON 顺序更改时保护自己。例如:

json_player['name']

是否有人能告诉我如何实现这个功能?

英文:

I am using python and have the following JSON block, json_player, which is stored as a list:

[
    {
        "id": "name",
        "value": "john"
    },
    {
        "id": "sport",
        "value": "baseball"
    },
    {
        "id": "age",
        "value": "20"
    }
]

Note that this is the resulting block from:

json_object = json.loads(df['customFields'])
json_player = json_object['player']

I know that I can access individual strings within json_player using the following code:

json_player[0]['value']

Which would return the string john.

However, I would like to be able to call individual key-value pairs by name, rather than index, in order to protect myself if underlying JSON order changes. For example:

json_player['name']

would return john. Can anyone tell me how I would do this?

答案1

得分: 3

你可以使用 字典推导式 轻松构建字典:

data = {
    item["id"]: item["value"]
    for item in json_player
}
print(data)
# => {'name': 'john', 'sport': 'baseball', 'age': '20'}
英文:

You can easily construct the dictionary using a dict comprehension:

data = {
    item["id"]: item["value"]
    for item in json_player
}
print(data)
# => {'name': 'john', 'sport': 'baseball', 'age': '20'}

huangapple
  • 本文由 发表于 2023年8月10日 10:26:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76872288.html
匿名

发表评论

匿名网友

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

确定