jKraut jKraut - 4 months ago 18
Python Question

Python dictionary get distinct list counts

I've been working with trying to get an output in which Dictionary values are distinct lists with a count.

Here is my input data:

event = [{'1a': ['tv', 'energy star tv']}, {'2a':['tv', 'energy star tv']}, {'3a':['tv', 'brand']}]


Here is my desired output:

{'tv': ['energy star tv', 2],['brand', 1]}


Here is my current code:

event = [{'1a': ['tv', 'energy star tv']}, {'2a':['tv', 'energy star tv']}, {'3a':['tv', 'brand']}]
event_values = []

for e in event:
event_values.append(e.values())

e_dict = {}

for e in event_values:
if 'tv' == e[0][0]:
new_key = ''
new_key = e[0][0]

new_facet_value = ''
new_facet_value = e[0][1]

if new_key not in e_dict: # detects first key is not in dict
e_dict[new_key] = [new_facet_value, 1]
else:
i = e_dict[new_key][1] + 1 # increments count
j = []
j = [new_facet_value, i]
e_dict[new_key] = j
print e_dict


Here is my current (undesired) output:

{'tv': ['brand', 3]}

Answer

{'tv': ['energy star tv', 2],['brand', 1]} isn't legal python, assume you mean a list of lists as the value, or a more appropriate data structure like a dictionary.

You can use a collections.Counter() to simplify the problem:

from collections import Counter
event = [{'1a': ['tv', 'energy star tv']}, {'2a':['tv', 'energy star tv']}, {'3a':['tv', 'brand']}]
r = {}
for e in event:
    for a, b in e.values():
        r.setdefault(a, Counter())[b] += 1
print(r)

Output:

{'tv': Counter({'brand': 1, 'energy star tv': 2})}

It's a simple exercise to translate the Counter back to a list of lists.

You could also combine it with a collections.defaultdict to make the code more readable:

from collections import Counter, defaultdict
event = [{'1a': ['tv', 'energy star tv']}, {'2a':['tv', 'energy star tv']}, {'3a':['tv', 'brand']}]
r = defaultdict(Counter)
for e in event:
    for a, b in e.values():
        r[a][b] += 1
print(r)

Output:

defaultdict(collections.Counter, {'tv': Counter({'brand': 1, 'energy star tv': 2})})