我有一个python字典,如:
pydict = {"group1":[{"name":"john","count":1},{"name":"johny","count":2}],
"group2":[{"name":"raj","count":1},{"name":"johny","count":4}],
"group3":[{"name":"ram","count":1},{"name":"raj","count":4}]
}
我想迭代pydict,我想维护一个如下表:
Name group1 group2 group3
johny true true
raj true true
我尝试使用python sets ,因此可以将pydict中的每个键元素分配给集合,最后进行交集,但它没有帮助。
请以最快的方式建议我。
答案 0 :(得分:0)
真正天真的实现方法是根据名称制作另一个dict
:
from collections import defaultdict
names = defaultdict(set)
for group in sorted(pydict.keys()):
for person in pydict[group]:
names[person["name"]].add(group)
for key, val in names.iteritems():
print key, ":", list(val)
输出
johny:[' group1',' group2']
约翰:[' group1']raj:[' group3',' group2']
ram:[' group3']