给定一个字典列表(每个字典都有相同的键),我想要与给定键相关联的不同值的总数
$ li = [{1:2,2:3},{1:2,2:4}] $
预期输出为{1:1,2:2}
我想出了以下代码......有没有更好的方法呢?
counts = {}
values = {}
for i in li:
for key,item in i.items():
try:
if item in values[key]:
continue
except KeyError:
else:
try:
counts[key] += 1
except KeyError:
counts[key] = 1
try:
values[key].append(item)
except KeyError:
values[key] = [item]
答案 0 :(得分:4)
这样的事情可能更直接:
from collections import defaultdict
counts = defaultdict(set)
for mydict in li:
for k, v in mydict.items():
counts[k].add(v)
负责收集/计算值。要像你想要的那样显示它们,这会让你到达那里:
print dict((k, len(v)) for k, v in counts.items())
# prints {1: 1, 2: 2}
答案 1 :(得分:1)
这是另一种选择:
from collections import defaultdict
counts = defaultdict(int)
for k, v in set(pair for d in li for pair in d.items()):
counts[k] += 1
结果:
>>> counts
defaultdict(<type 'int'>, {1: 1, 2: 2})
答案 2 :(得分:0)
你可以这样:
li = [{1:2,2:3},{1:2,2:4}]
def makesets(x, y):
for k, v in x.iteritems():
v.add(y[k])
return x
distinctValues = reduce(makesets, li, dict((k, set()) for k in li[0].keys()))
counts = dict((k, len(v)) for k, v in distinctValues.iteritems())
print counts
当我运行它时会打印:
{1: 1, 2: 2}
这是期望的结果。
答案 3 :(得分:0)
counts = {}
values = {}
for i in li:
for key,item in i.items():
if not (key in values.keys()):
values[key] = set()
values[key].add(item)
for key in values.keys():
counts[key] = len(values[key])
答案 4 :(得分:0)
使用展平列表,如果dicts的长度不一样:
li=[{1: 2, 2: 3}, {1: 2, 2: 4}, {1: 3}]
dic={}
for i,j in [item for sublist in li for item in sublist.items()]:
dic[i] = dic[i]+1 if i in dic else 1