从字典、嵌套字典、列表中获取键,并检查它出现的次数



所以基本上,我试图写一个代码,从json文件中获取字典。这本字典包含其他字典、列表等。我试图从json(结果,x1,x2,x3,y1,y2,a1,b1)中获取所有键,并显示每个键出现的时间,同时检查嵌套的字典和列表。

代码:

# open data
import json
with open('list.json') as f:
my_dict = json.load(f)
k=int()
def count_k_v(k):
keys=0
if type(k)==dict:
for value in k.keys():
if isinstance(k[value], (dict,list)):
keys+=1
k=count_k_v(k[value])
keys+=k
else:
keys+=1
elif type(k)==list:
for value in k:
if isinstance(value,(list,dict)):
k=count_k_v(value)
keys+=k
else:
keys+=1
return keys

#['results','x1','x2','y1','x3','y2','a1','b1']     
for key, value in my_dict:
print("{}".format(key,value))   
#FOUND 8 KEYS.
print("Found {} keys.",count_k_v(my_dict))
#RESULTS FOUND 1 TIME
#X1 KEY FOUND 1 TIME
#X2 KEY FOUND 1 TIME
#Y1 KEY FOUND 1 TIME
#X3 KEY FOUND 1 TIME
#Y2 KEY FOUND 1 TIME
#A1 KEY FOUND 1 TIME
#B1 KEY FOUND 1 TIME
for key in my_dict:

JSON:

{
"results":[
{
"x1":5
},
{
"x2":5,
"y1":[
1,
2,
3
]
},
{
"x3":5,
"y2":{
"a1":2,
"b1":67
}
}
]
}

尝试打印:

['results','x1','x2','y1','x3','y2','a1','b1']
FOUND 8 KEYS.
RESULTS FOUND 1 TIME
X1 KEY FOUND 1 TIME
X2 KEY FOUND 1 TIME
Y1 KEY FOUND 1 TIME
X3 KEY FOUND 1 TIME
Y2 KEY FOUND 1 TIME
A1 KEY FOUND 1 TIME
B1 KEY FOUND 1 TIME

您可以使用递归方法,collections.Counter:

from collections import Counter
def get_result(d):
keys = []
def recurse(d):
if isinstance(d, dict):
for k, v in d.items():
keys.append(k)
if isinstance(v, (dict, list)):
recurse(v)
elif isinstance(d, list):
for item in d:
if isinstance(item, (dict, list)):
recurse(item)
else:
return
recurse(d)
print(keys)
print(f'found {len(keys)} keys.'.upper())
for k, v in Counter(keys).items():
print(f'{k} key found {v} time'.upper())
get_result(my_dict)

输出:

['results', 'x1', 'x2', 'y1', 'x3', 'y2', 'a1', 'b1']
FOUND 8 KEYS.
RESULTS KEY FOUND 1 TIME
X1 KEY FOUND 1 TIME
X2 KEY FOUND 1 TIME
Y1 KEY FOUND 1 TIME
X3 KEY FOUND 1 TIME
Y2 KEY FOUND 1 TIME
A1 KEY FOUND 1 TIME
B1 KEY FOUND 1 TIME

或者,你可以用re解析json string[不是完全证明的,建议用于简单的json]:

import re
def get_result(json_str):
keys = re.findall(r'"([^"]+?)"s*:', json_str)
print(keys)
print(f'found {len(keys)} keys'.upper())
for k, v in Counter(keys).items():
print(f'{k} key found {v} time'.upper())
print(get_result(json.dumps(my_dict)))

输出:

['results', 'x1', 'x2', 'y1', 'x3', 'y2', 'a1', 'b1']
FOUND 8 KEYS.
RESULTS KEY FOUND 1 TIME
X1 KEY FOUND 1 TIME
X2 KEY FOUND 1 TIME
Y1 KEY FOUND 1 TIME
X3 KEY FOUND 1 TIME
Y2 KEY FOUND 1 TIME
A1 KEY FOUND 1 TIME
B1 KEY FOUND 1 TIME

相关内容

  • 没有找到相关文章

最新更新