[英]Elements of dict of sets in python
I have a dictionary like this: 我有一本这样的字典:
dict1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5: set([2]), 6: set([])}
and from this dictionary I want to build another dictionary that count the occurrences of keys in dict1 in every other value ,that is the results should be: 从这个字典中,我想建立另一个字典,该字典计算dict1中每个其他值中键的出现次数,即结果应该是:
result_dict = {0: 1, 1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1}
My code was this : 我的代码是这样的:
dict1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5:set([2]), 6: set([])}
result_dict = {}
for pair in dict1.keys():
temp_dict = list(dict1.keys())
del temp_dict[pair]
count = 0
for other_pairs in temp_dict :
if pair in dict1[other_pairs]:
count = count + 1
result_dict[pair] = count
The problem with this code is that it is very slow with large set of data. 此代码的问题在于,处理大量数据时,它的运行速度非常慢。 Another attempt was in a single line, like this : 另一尝试是在一行中,如下所示:
result_dict = dict((key ,dict1.values().count(key)) for key in dict1.keys())
but it gives me wrong results, since values of dict1 are sets: 但这会给我错误的结果,因为dict1的值已设置:
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
thanks a lot in advance 提前非常感谢
I suppose, for a first stab, I would figure out which values are there: 我想,对于第一个步骤,我想知道那里有哪些值:
all_values = set().union(*dict1.values())
Then I'd try to count how many times each value occurred: 然后,我尝试计算每个值出现了多少次:
result_dict = {}
for v in all_values:
result_dict[v] = sum(v in dict1[key] for key in dict1)
Another approach would be to use a collections.Counter
: 另一种方法是使用collections.Counter
:
result_dict = Counter(v for set_ in dict1.values() for v in set_)
This is probably "cleaner" than my first solution -- but it does involve a nested comprehension which can be a little difficult to grok. 这可能比我的第一个解决方案“更干净”-但这确实涉及嵌套的理解,这可能有点难以理解。 It does work however: 它确实可以工作:
>>> from collections import Counter
>>> dict1
{0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5: set([2]), 6: set([])}
>>> result_dict = Counter(v for set_ in dict1.values() for v in set_)
Just create a second dictionary using the keys from dict1
, with values initiated at 0
. 只需使用dict1
的键创建第二个字典,值从0
开始。 Then iterate through the values in the sets of dict1
, incrementing values of result_dict
as you go. 然后遍历dict1
集合中的值,并随着dict1
增加而递增result_dict
值。 The runtime is O(n) , where n is the aggregate number of values in sets of dict1
. 运行时为O(n) ,其中n是dict1
组中值的dict1
。
dict1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5:set([2]), 6: set([])}
result_dict = dict.fromkeys(dict1.keys(), 0)
# {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
for i in dict1.keys():
for j in dict1[i]:
result_dict[j] += 1
print result_dict
# {0: 1, 1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.