比较两个JSON dicts中的元素,并将差异作为比率或百分比

时间:2016-01-31 10:46:56

标签: python json

我有一个JSON对象,我正在进行一些数据操作。我希望得到差异作为一个比例,这样我就能更准确地对我的词典中的元素进行排名。

[{condition: functional, location:Sydney }, {condition:functional, location: Adelaide}, {condition:broken, location:Sydney}]

我可以得到位置不起作用的点数:

filter(lambda x: x['condition']!='functional', json_obj)

但我想以百分比的形式返回。

3 个答案:

答案 0 :(得分:1)

很简单:

a = [{'condition': 'functional', 'location':'Sydney' }, {'condition':'functional', 'location': 'Adelaide'}, {'condition':'broken', 'location':'Sydney'}]

b = filter(lambda x: x['condition']!='functional', a)

all_locations = [item['location'] for item in b]

result = {}

for location in all_locations:
    if location not in result.keys():
        result[location] = all_locations.count(location)*100/float(len(all_locations))

print result

它将返回每个位置的百分比

答案 1 :(得分:1)

您可以尝试Counterdefaultdict,如下所示 -

from collections import Counter,defaultdict

d = [{'condition': 'functional', 'location':'Sydney' }, {'condition':'functional', 'location': 'Adelaide'}, {'condition':'broken', 'location':'Sydney'}]

cities = [j['location'] for j in d]

#initialize data
data = defaultdict(float)
for city in cities:
    data[city]=0
#Count occurrances of a single city as a counter dictionary
counters = Counter((i['location'] for i in d))

#Do the calculation
for i in d:
    if i['condition']== 'functional':
        inc = (counters[i['location']]*100)/len(d)
        data[i['location']]+= float(inc)
    elif i['condition']== 'broken':
        dec = (counters[i['location']]*100)/len(d)
        data[i['location']]-=float(dec)
    else:
        raise Exception("Error")


print {k:"{0}%".format(v) for k,v in data.items()}

输出 -

{'Sydney': '0.0%', 'Adelaide': '33.0%'}

答案 2 :(得分:0)

这是你想要的吗?这比较了两个JSON dicts中的元素,并将差异作为比率,正如您在标题中所要求的那样。但是阅读问题正文,并不清楚你想要做什么。

这假设两个词典都具有相同的键。

def dictionary_similarity(d1, d2):
    return sum(d1[key] == d2[key] for key in d1) / float(len(d1))

dictionary_similarity(
    {'condition': 'functional', 'location': 'Sydney' }, 
    {'condition': 'functional', 'location': 'Adelaide'},)

0.5