使用相似的键但值不同的方法对嵌套字典进行迭代 [英] Iterate over Nested dictionary with similar keys but different values
本文介绍了使用相似的键但值不同的方法对嵌套字典进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
{
"matchesPlayed":{"label":"Matches Played","value":7}
, "matches":[
{
"date":"21 Jun"
,"hteamcode":"ESP"
,"hteamName":"Spain"
,"ateamcode":"HON"
,"ateamName":"Honduras"
,"score":"2:0 (1:0)"
}
,
{
"date":"25 Jun"
,"hteamcode":"CHI"
,"hteamName":"Chile"
,"ateamcode":"ESP"
,"ateamName":"Spain"
,"score":"1:2 (0:2)"
}
,
{
"date":"07 Jul"
,"hteamcode":"GER"
,"hteamName":"Germany"
,"ateamcode":"ESP"
,"ateamName":"Spain"
}
,
{
"date":"29 Jun"
,"hteamcode":"ESP"
,"hteamName":"Spain"
,"ateamcode":"POR"
,"ateamName":"Portugal"
,"score":"1:0 (0:0)"
}
,
{
"date":"11 Jul"
,"hteamcode":"NED"
,"hteamName":"Netherlands"
,"ateamcode":"ESP"
,"ateamName":"Spain"
,"score":"0:1 a.e.t."
}
,
{
"date":"03 Jul"
,"hteamcode":"PAR"
,"hteamName":"Paraguay"
,"ateamcode":"ESP"
,"ateamName":"Spain"
,"score":"0:1 (0:0)"
}
,
{
"date":"16 Jun"
,"hteamcode":"ESP"
,"hteamName":"Spain"
,"ateamcode":"SUI"
,"ateamName":"Switzerland"
,"score":"0:1 (0:0)"
}
]
}
这是我的Json文件的副本.我如何遍历json并进行列表/或打印一个特定的键(例如:"hteamName"),这在不同的数组中是相似的,但是具有不同的值.从上一个问题开始,我得到了一些可以迭代嵌套字典的代码,但是它只能找到具有唯一值的唯一键.
This is a copy of my Json file. How can I loop through the json and make a list/or print a particular key (example: "hteamName"), which is similar in different arrays but with different values. From a previous question, I got some codes that could iterate through a nested dictionary, but it only finds unique keys with unique values.
def search(nest, nestitems):
found = []
for key, value in nest.iteritems():
if key == nestitems:
found.append(value)
elif isinstance(value, dict):
found.extend(search(value, nestitems))
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
found.extend(search(item, nestitems))
else:
if key == nestitems:
found.append(value)
return found
推荐答案
尝试以下简单版本:
with open(r'C:/Json/Spain.json') as f:
data = json.load(f)
for match in data['matches']:
print(match['hteamName'])
它应该使您开始其余的工作.
It should get you started with the rest of your work.
这篇关于使用相似的键但值不同的方法对嵌套字典进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文