gpt4 book ai didi

Python-如何在类似字典的 json 字符串中检索与同一键关联的多个值?

转载 作者:太空宇宙 更新时间:2023-11-04 07:16:46 25 4
gpt4 key购买 nike

好的,所以我有来自网页的 json 源代码,在此源代码中,同一个词(“作者”)用作多个值的键。如何检索“作者”的所有值?

例如

"author": "SampleMan", "author":"NonSampleMan", "author":"BoringMan"

如何让 Python 返回 ["SampleMan", "NonSampleMan", "BoringMan"]

最佳答案

您可以将 object_pairs_hook 传递给 json.loads这将收集具有相同键值的列表:

from collections import defaultdict
import json

s = '{"author": "SampleMan", "author":"NonSampleMan", "author":"BoringMan", "foo":"bar", "bar": [1]}'

def hook(pairs):
d = defaultdict(list)
for k, v in pairs:
d[k].append(v)

return {k: v if len(v) > 1 else v[0] for k, v in d.items()}

print(json.loads(s, object_pairs_hook=hook))

输出:

{'bar': [1], 'author': ['SampleMan', 'NonSampleMan', 'BoringMan'], 'foo': 'bar'}

在上面的钩子(Hook)中接收 list(key, value) 元组存储到 defaultdict其中值是列表。一旦对元组进行迭代,它将生成结果 dict,如果有多个具有给定键的项目,则值为列表。

Python 文档对钩子(Hook)的描述如下:

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict() will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.

关于Python-如何在类似字典的 json 字符串中检索与同一键关联的多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41518671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com