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

2024-10-01 04:53:48 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我有一个网页的json源代码,在这个源代码中,同一个单词(“author”)被用作多个值的键。如何检索“author”的所有值?在

例如

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

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


Tags: json网页源代码单词authorsamplemannonsamplemanboringman
1条回答
网友
1楼 · 发布于 2024-10-01 04:53:48

您可以将object_pairs_hook传递给^{},后者将使用相同的键将值收集到列表中:

^{1}$

输出:

^{pr2}$

在上面的钩子接收(key, value)元组的list,它将这些元组存储到^{},其中值是列表。一旦迭代元组,它将生成结果dict,其中value是list,如果有多个项具有给定的键。在

Python文档对钩子有以下描述:

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.

相关问题 更多 >