counts = defaultdict(int)
for elem in sets: #list of sets
for _ in elem: #each set contains elements that may be duplicates among the sets
counts[_] += 1
Is there a way to use dict comprehension for code like this?
counts = defaultdict(int)
for elem in sets: #list of sets
for _ in elem: #each set contains elements that may be duplicates among the sets
counts[_] += 1
Is there a way to use dict comprehension for code like this?
Don't use a list comprehension for side effects (i.e. updating counts
).
Instead, if you replace defaultdict(int)
with Counter
, you can write the solution in one line. (I assume your end goal is to make your code shorter/cleaner.)
sets = [
{1, 2, 3},
{1, 2},
{3},
{3}]
# ---
from collections import Counter
counts = Counter(x for s in sets for x in s)
print(counts) # -> Counter({3: 3, 1: 2, 2: 2})
itertools.chain.from_iterable(sets)
.If you are adamant at using list comprehension, you can do this way:
>>> counts = {1:4, 2:5, 3:8, 4:2, 5:9}
>>> sets = [{2,3}, {3,1}, {2}]
>>> [[counts.update({e: counts[e]+1}) for e in si] for si in sets]
[[None, None], [None, None], [None]]
>>> counts
{1: 5, 2: 7, 3: 10, 4: 2, 5: 9}
But yes, as others suggested, you can do it using Counter:
#1: use Counter to get new counts from sets
#2: merge both new & default counters
#3: get Counter back into your dictionary
With sample input:
>>> counts = {1:4, 2:5, 3:8, 4:2, 5:9}
>>> sets = [{2,3}, {3,1}, {2}]
>>> from collections import Counter
>>> cntr_new = Counter(x for s in sets for x in s)
>>> cntr_new
Counter({2: 2, 3: 2, 1: 1})
>>> cntr_orig = Counter(counts)
>>> cntr_final = cntr_orig + cntr_new
Final result:
>>> dict(cntr_final)
{1: 5, 2: 7, 3: 10, 4: 2, 5: 9}