使用类似的键但不同的值迭代嵌套字典

时间:2014-05-08 11:29:02

标签: python json search dictionary

    {
       "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"),这在不同的数组中是相似的,但具有不同的值。 从上一个问题开始,我得到了一些可以遍历嵌套字典的代码,但它只能找到具有唯一值的唯一键。

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 

2 个答案:

答案 0 :(得分:1)

["hteamName :"+ x.get("hteamName") for x in d["matches"] ]
['hteamName :Spain', 'hteamName :Chile', 'hteamName :Germany', 'hteamName :Spain',    'hteamName :Netherlands', 'hteamName :Paraguay', 'hteamName :Spain']

在一个功能中:

def search(d, k,nested):
    result=[]
    for n in d[nested]:
        result.append('{0} : {1}'.format(k,n.get(k)))
    return result

search(d,"hteamName","matches")
['hteamName : Spain', 'hteamName : Chile', 'hteamName : Germany', 'hteamName : Spain', 'hteamName : Netherlands', 'hteamName : Paraguay', 'hteamName : Spain']

这应该让你开始。

答案 1 :(得分:1)

试试这个更简单的版本:

with open(r'C:/Json/Spain.json') as f:
    data = json.load(f)

for match in data['matches']:
    print(match['hteamName'])

它应该让你开始完成其余的工作。