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

标签 python arrays json hashtable reddit

好的,所以我有来自网页的 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/

相关文章:

java - 线程 "main"java.lang.NoClassDefFoundError : org/json/simple/JSONObject - java commandline runtime error 中出现异常

java - 写入扩展数组

iphone - 使用 AFNetworking 和 HTTP 基本身份验证

python - 如何将 Pylint 或其他 linters 与 Jupyter 笔记本一起使用?

python - 相当于 python 的 shell "set -x"

Python,lxml - 获取兄弟标签的(孙)子文本

c - 使用临时变量或直接从数组更有效?

python - Pandas 将年份列转换为日期列

C数组循环

javascript - 循环 URL 并使用数组加载取决于 ID