Barry Marples
Barry Marples

Reputation: 17

Finding the most common element

I have managed to identify which element appears most often but then I'm struggling to store that value in a variable, or even all items in a dictionary.

gather_occurrences = ['CAT', 'BIRD', 'DOG', 'BIRD', 'DOG', 'CAT', 'BIRD', 'RAT']
unique_occurrences = set(gather_occurances)
unique_occurrences = {'CAT', 'DOG', 'BIRD', 'RAT'}

counting = 1

for x in unique_occurrences:
    count = gather_occurrences.count(x)
    each_item = { counting : {x : count }}
    counting += 1
    all_data = []
    all_data.append(each_item)
    print(each_item)

print(all_data)

Output:

{1: {'CAT': 2}}
{2: {'BIRD': 3}}
{3: {'RAT': 1}}
{4: {'DOG': 2}}

[{4: {'DOG': 2}}]

Each time I run the code the all_data part e.g. [{4: {'DOG': 2}}] only contains 1 piece of data instead of a list or a dictionary.

I keep swapping lines of code in the for loop around I've tried .extend instead of .append but I never seem to be able to get the output I want.

Upvotes: 1

Views: 47

Answers (2)

Gderu
Gderu

Reputation: 131

You should move all_data = [] outside of the for loop. Your problem occurs because each time it loops, you reset all_data, and so only the last thing you added to it remains.

Upvotes: 0

azro
azro

Reputation: 54148

The problem is that you define the holding structure in the loop, so you keep overwriting it, you need to define it before. Also is seems useless to have a 2-level dict for each value

gather_occurances = ['CAT', 'BIRD', 'DOG', 'BIRD', 'DOG', 'CAT', 'BIRD', 'RAT']
unique_occrrences = set(gather_occurances)
all_data = []
for x in unique_occrrences:
    all_data.append({x: gather_occurances.count(x)})
print(all_data)
#  [{'CAT': 2}, {'BIRD': 3}, {'DOG': 2}, {'RAT': 1}]

Note built-in collections.Counter

from collections import Counter

c = Counter(gather_occurances)
print(c)          # {'BIRD': 3, 'CAT': 2, 'DOG': 2, 'RAT': 1}
print(c.items())  # [('CAT', 2), ('BIRD', 3), ('DOG', 2), ('RAT', 1)]

Upvotes: 1

Related Questions