python - How to extract values from each entry in nested dictionary?
问题描述
I have a program that parses a maven dependency tree & organizes the data how I want. I'm unsure of how to index into the data properly in order to return the it. Here is an excerpt of what the outputted data from the maven dependency tree parser looks like (using pprint).
[{'name': 'org.antlr'},
{'type': 'dependency'},
{'metadata': [{'groupId': 'org.antlr'},
{'artifactId': 'antlr4',
'children': [({'name': 'org.antlr'},
{'type': 'dependency'},
{'metadata': [{'groupId': 'org.antlr'},
{'artifactId': 'antlr4-runtime'}]}),
({'name': 'org.antlr'},
{'type': 'dependency'},
{'metadata': [{'groupId': 'org.antlr'},
{'artifactId': 'antlr-runtime'}]}),
({'name': 'org.antlr'},
{'type': 'dependency'},
{'metadata': [{'groupId': 'org.antlr'},
{'artifactId': 'ST4'}]}),
({'name': 'org.abego.treelayout'},
{'type': 'dependency'},
{'metadata': [{'groupId': 'org.abego.treelayout'},
{'artifactId': 'org.abego.treelayout.core'}]}),
({'name': 'org.glassfish'},
{'type': 'dependency'},
{'metadata': [{'groupId': 'org.glassfish'},
{'artifactId': 'javax.json'}]}),
({'name': 'com.ibm.icu'},
{'type': 'dependency'},
{'metadata': [{'groupId': 'com.ibm.icu'},
{'artifactId': 'icu4j'}]})]}]}]
I have tried:
pprint([name for name in parsedTree[0]])
or
pprint(parsedTree[0:1])
or variations of these where parsedTree is the output shown above.
Ultimately I want to return only the names of each perhaps using recursion or a generator to prepare this info for an API call. I do not know how to index & extract name alone (without the metadata or type). Is there a way to do this? Thank you in advance. I want to get each name separately so that if I do something like Beans.name it returns
org.antlr
org.antlr
org.antlr
org.antlr
org.antlr
org.abego.treelayout
org.glassfish
com.ibm.icu
解决方案
My previous answer was wrong, I think this should work:
def get_all_names(parsed_tree, li):
if not isinstance(parsed_tree, list) and not isinstance(parsed_tree, tuple):
return li
def get_all_names_dict(dictionary, li):
if not isinstance(dictionary, dict):
get_all_names(dictionary, li)
return
for key in dictionary.keys():
if key == 'name':
li.append(dictionary[key])
elif isinstance(dictionary[key], dict):
get_all_names_dict(dictionary[key], li)
elif isinstance(dictionary[key], list):
get_all_names(dictionary[key], li)
elif isinstance(dictionary[key], tuple):
get_all_names(dictionary[key], tuple)
for val in parsed_tree:
get_all_names_dict(val, li)
return li
print('\n'.join(get_all_names(parsedTree, [])))
Sorry for the wait!
推荐阅读
- css - 排列元素,无论其大小
- testng - AWS 设备场功能
- javascript - 具有多个分享/喜欢的结果页面
- angularjs - Node-Red 仪表板:是否可以在模板节点内发送和获取 html GET 请求的响应?
- bash - 从 Windows 在某个目录中启动 bash
- postgresql - PostgreSQL / PostGIS 在查询中使用变量
- python-2.7 - 无法获得代表
- javafx - JavaFX setOnKeyReleased vs textProperty 监听器
- php - 通过一个按钮在浏览器中查看我的 PHP 源代码
- c++ - Qt Creator 和 Qt 桌面应用程序的菜单不可见或丢失