首页 > 解决方案 > python中的嵌套列表和字典

问题描述

我在 python 中有 3 个不同的字典,比如这些

d1 = {'simple_key':'hello'}
d2 = {'k1':{'k2':'hello'}}
d3 = {'k1':[{'nest_key':['this is deep',['hello']]}]}

我想从这些词典中获取“你好”这个词。但是我面临的问题是我想找到一种通用的方法来提取它。我该怎么做?

标签: pythondictionary

解决方案


要使用 value 获取 dict 中的键路径,您可以将其展平为 json。

>>> from json_flatten import flatten
>>> d1 = {'simple_key':'hello'}
>>> d2 = {'k1':{'k2':'hello'}}
>>> d3 = {'k1':[{'nest_key':['this is deep',['hello']]}]}
>>> flatten(d2)
{'k1.k2': 'hello'}
>>> flat = flatten(d3)
{'k1.0.nest_key.0': 'this is deep', 'k1.0.nest_key.1.0': 'hello'}

要查找匹配的键,请使用,

>>> [k for k, v in flat.items() if v == 'hello']
['k1.0.nest_key.1.0']

JSON 展平


推荐阅读