jKraut
jKraut

Reputation: 2487

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]}

Upvotes: 1

Views: 91

Answers (2)

Valera Grishin
Valera Grishin

Reputation: 441

this code:

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

e_dict = {}

for key, value in [d.values()[0] for d in event]:
    if key in e_dict:
        if value in e_dict[key]:
            e_dict[key][value] = e_dict[key][value]+1
        else:
            e_dict[key][value] = 1
    else:
        e_dict[key] = {value: 1}

print e_dict

will produce:

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

Upvotes: 0

AChampion
AChampion

Reputation: 30258

{'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})})

Upvotes: 1

Related Questions