英文:
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'}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论