Python:如果其他值为true,则计算嵌套字典中值的出现次数



我有一个嵌套的字典,看起来像这样:

{
1: {'Name': {'John'}, 'Answer': {'yes'}, 'Country': {'USA'}}, 
2: {'Name': {'Julia'}, 'Answer': {'no'}, 'Country': {'Hong Kong'}}
3: {'Name': {'Adam'}, 'Answer': {'yes'}, 'Country': {'Hong Kong'}}
}

我现在需要获得每个国家的发生次数以及回答是或否的人数。目前,我只收集每个国家的出现次数:

nationalities = ['USA', 'Hong Kong', 'France' ...]
for countries in nationalities:
cnt =[item for l in [v2 for v1 in dictionary1.values() for v2 in v1.values()] for item in l].count(countries)
result.append(countries + ': ' + str(cnt))

所以使用我的数据表,我得到了类似的东西

['Hong Kong: 2', 'France: 2', 'Italy: 3']

然而,我想得到回答是和否的人的比例。这样我就得到了一个['Hong Kong: 2 1 1']形式的列表,其中第一个数字是总数,第二个和第三个数字分别是是和否。

感谢的帮助

以下是一个可能的解决方案,使用defaultdict通过对每个country:的答案数等于yesno来生成结果字典

from collections import defaultdict
dictionary1 = {
1: {'Name': {'John'}, 'Answer': {'yes'}, 'Country': {'USA'}}, 
2: {'Name': {'Julia'}, 'Answer': {'no'}, 'Country': {'Hong Kong'}},
3: {'Name': {'Adam'}, 'Answer': {'yes'}, 'Country': {'Hong Kong'}}
}
nationalities = ['USA', 'Hong Kong', 'France']
result = defaultdict(list)
for countries in nationalities:
[yes, no] = [sum(list(d['Answer'])[0] == answer and list(d['Country'])[0] == countries for d in dictionary1.values()) for answer in ['yes', 'no']]
result[countries] = [ yes+no, yes, no ]

print(dict(result))

对于您的样本数据,这将给出

{
'USA': [1, 1, 0],
'Hong Kong': [2, 1, 1],
'France': [0, 0, 0]
}

然后,您可以通过将其转换为字符串列表

result = [ f"{key}: {' '.join(map(str, counts))}" for key, counts in result.items()]

它给出:

['USA: 1 1 0', 'Hong Kong: 2 1 1', 'France: 0 0 0']
a={
1: {'Name': {'John'}, 'Answer': {'yes'}, 'Country': {'USA'}}, 
2: {'Name': {'Julia'}, 'Answer': {'no'}, 'Country': {'Hong Kong'}},
3: {'Name': {'Adam'}, 'Answer': {'yes'}, 'Country': {'Hong Kong'}}
}
results=[]
nationalities = ['USA', 'Hong Kong', 'France']
for country in nationalities:
countryyes=0
countryno=0
for row in a.values():
if str(row['Country'])[2:-2] == country:
if str(row['Answer'])[2:-2] == 'yes':
countryyes+=1
if str(row['Answer'])[2:-2] == 'no':
countryno+=1
results.append(country+': '+str(countryyes+countryno)+' '+str(countryyes)+' '+str(countryno))

我想做几个笔记。首先,我将countries改为country(在for循环中使用复数名称是不正常的(。其次,我想评论一下,如果你上面的代码在一组中都有名字、答案和国家,我认为你最好把它改成字符串。

我会使用Counter来计数答案,使用groupby()来按国家/地区对条目进行分组:

from collections import Counter
from operator import itemgetter
from itertools import groupby
dictionary1 = {...}  # input data
group_func = itemgetter('Country')
result = []
for (country, *_), items in groupby(sorted(dictionary1.values(), key=group_func), group_func):
answers = Counter(answer.lower() for i in items for answer in i['Answer'])
result.append(f'{country} {sum(answers.values())} {answers.get("yes", 0)} {answers.get("no", 0)}')

最新更新