python2.7:遍历dict列表并评估所需的值

2024-06-13 01:32:11 发布

您现在位置:Python中文网/ 问答频道 /正文

代码:

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

场景:从上面的数据,我想检查是否在所有的“地区”(键)如果“状态”(键)是“确定”(值)或“无”(值),如果“状态”(键)是“无”(值),那么它应该返回我的细节(值)的特定“地区”(键)连同“名称”(键)。你知道吗

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

Europe, Rebecca

Asia, (kim, jen)

任何帮助都将不胜感激。你知道吗


Tags: nameinimportnoneforagedatastatus
1条回答
网友
1楼 · 发布于 2024-06-13 01:32:11

这很难看,但你可能想问:

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)

相关问题 更多 >