[英]Parse output from json python
I have a json below, and I want to parse out value from this dict.我在下面有一个 json,我想从这个字典中解析出值。
I can do something like this to get one specific value我可以做这样的事情来获得一个特定的价值
print(abc['everything']['A']['1']['tree']['value'])
But, what is best way to parse out all "value?"但是,解析所有“价值”的最佳方法是什么? I want to output good, bad, good.
我想 output 好,坏,好。
abc = {'everything': {'A': {'1': {'tree': {'value': 'good'}}},
'B': {'5': {'tree1': {'value': 'bad'}}},
'C': {'30': {'tree2': {'value': 'good'}}}}}
If you are willing to use pandas
, you could just do something like this:如果您愿意使用
pandas
,您可以这样做:
import pandas as pd
abc = {'everything': {'A': {'1': {'tree': {'value': 'good'}}},
'B': {'5': {'tree1': {'value': 'bad'}}},
'C': {'30': {'tree2': {'value': 'good'}}}}}
df = pd.json_normalize(abc)
print(df.values)
[['good' 'bad' 'good']]
Without any extra libraries, you will have to iterate through your nested dictionary:如果没有任何额外的库,您将不得不遍历您的嵌套字典:
values = [abc['everything'][e][k][k1]['value'] for e in abc['everything'] for k in abc['everything'][e] for k1 in abc['everything'][e][k]]
print(values)
Provided your keys and dictionaries have a value
somewhere, you can try this:如果你的键和字典在某处有
value
,你可以试试这个:
value
key exists, then return that.value
键存在,然后返回它。 Note that there are other ways of doing this.value
key and return.value
键下的结果并返回。# Define function
def get(d):
while not "value" in d:
d = list(d.values())[0]
return d["value"]
# Get the results from your example
results = [get(v) for v in list(abc["everything"].values())]
['good', 'bad', 'good']
A Recursive way:递归方式:
def fun(my_dict, values=[]):
if not isinstance(my_dict, dict):
return values
for i, j in my_dict.items():
if i == 'value':
values.append(j)
else:
values = fun(j, values)
return values
abc = {'everything': {'A': {'1': {'tree': {'value': 'good'}}},
'B': {'5': {'tree1': {'value': 'bad'}}},
'C': {'30': {'tree2': {'value': 'good'}}}}}
data = fun(abc)
print(data)
Output:
['good', 'bad', 'good']
Firstly, the syntax you are using is incorrect.首先,您使用的语法不正确。
If you are using pandas, you can code like如果您使用的是 pandas,您可以编写如下代码
import pandas as pd导入 pandas 作为 pd
df4 = pd.DataFrame({"TreeType": ["Tree1", "Tree2", "Tree3"], "Values": ["Good", "Bad","Good"]}) df4 = pd.DataFrame({"TreeType": ["Tree1", "Tree2", "Tree3"], "Values": ["Good", "Bad","Good"]})
df4.index = ["A","B","C"] df4.index = ["A","B","C"]
next just run the code df4, you would get the correct output.接下来只需运行代码 df4,您将得到正确的 output。
output: output:
TreeType Values
A Tree1 Good B Tree2 Bad C Tree3 Good A 树 1 好 B 树 2 坏 C 树 3 好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.