python - python中的嵌套列表和字典
问题描述
我在 python 中有 3 个不同的字典,比如这些
d1 = {'simple_key':'hello'}
d2 = {'k1':{'k2':'hello'}}
d3 = {'k1':[{'nest_key':['this is deep',['hello']]}]}
我想从这些词典中获取“你好”这个词。但是我面临的问题是我想找到一种通用的方法来提取它。我该怎么做?
解决方案
要使用 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']
推荐阅读
- php - 如何链接到页面的特定部分 HTML PHP
- c# - 当后端代码中的简单键值变量工作相同时,为什么要使用 redis 作为缓存层?
- google-apps-script - Google Slides Apps 脚本检索页面中的形状
- python-3.x - 在 KNeighborsClassifier 中使用自定义指标时,我不断收到“TypeError:只有整数标量数组可以转换为标量索引”
- java - JavaFX - 在使用选项卡时将 GUI 拆分为单独的类
- jquery - 通过函数调整电子窗口大小
- scheme - 匹配方案中的括号
- android - 当我使用 adb 显示 /sys/kernel/debug/tracing/available_filter_functions 时没有这样的设备
- python - 初始化以迭代抽象pyomo模型中的集合?
- angular-cli - 运行 ng serve -o 时出现错误