python2.7:迭代dicts列表并评估所需的值

时间:2017-02-22 22:55:37

标签: python json api parsing

代码:

import json
import urllib
URL = 'www.xyz.com'
data = json.load(urllib.urlopen(url)
print data   
[[{"Region":"Europe", "Details":[{"gender":"male", "name":"john", "age":"24", "status":"Ok"}, {"gender":"female", "name":"Rebecca", "age":"22", "status":"None"}], "country":"Germany"}], [{"Region":"Asia", "Details":[{"gender":"male", "name":"kim", "age":"27", "status":"None"}, {"gender":"male", "name":"jen", "age":"22", "status":"None"}], "country":"China"}]]
# here is what I have tried
for i in data:
     for j in i:
          for key in j.keys():
               dicx = j[key]
               for k in dicx:
                 if isinstance(k, dict) and k['status']=='None':
                 print (i['region'], k['name'])) #I wnant to store this value in a variable rather than printing.
#this is giving me the following output.  

Europe, Rebecca
Asia, kim
Asia, jen

场景:从上面的数据我想检查是否在所有“Region”(键)中“status”(键)是“Ok”(值)还是“None”(值),如果“status”( key)是“None”(值)然后它应该返回特定“Region”(键)的详细信息(值)以及“name”(键)。

例如: - 期望的输出(参考上面的数据)

Europe, Rebecca

Asia, (kim, jen)

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这非常难看,但可能确实想要你问:

matches = []
for i in data:  #
                # no changes here
                if isinstance(k, dict) and k['status']=='None':
                    # print (i[0]['Region'], k['name'])
                    matches.append(([i[0]['Region'], k['name']]))
from collections import defaultdict
res = defaultdict(list)

for k, v in matches:
    res[k].append(v)

for k, v in res.iteritems():
    if len(v) == 1:
        print'{}, {}'.format(k, v[0])
    else:
        print '{}, ({})'.format(k, ', '.join(map(str, v)))

编辑#1:

...
for k, v in matches:
    result[k].append(v)

mystr = ''

for k, v in result.iteritems():
    if len(v) == 1:
        mystr += '{}, {}'.format(k, v[0])
    else:
        mystr += ' {}, ({})'.format(k, ', '.join(map(str, v)))

print type(mystr)
print mystr

输出:

<type 'str'>
Europe, Rebecca Asia, (kim, jen)

有3个地区的例子:

<type 'str'>
Europe, Rebecca America, (David, Ricardo) Asia, (kim, jen)