How to select the most occurring element while creating a dictionary?

Viewed 360

I wanted to create an mapping between two arrays. But in python, doing this resulted in a mapping with last element getting picked.

array_1 = [0,0,0,1,2,3]
array_2 = [4,4,5,6,8,7]
mapping = dict(zip(array_1, array_2))
print(mapping)

The mapping resulted in {0: 5, 1: 6, 2: 8, 3: 7}

How to pick the most occurring element in this case 4 for key 0.

2 Answers

You can create a dictionary with key and a list of values for the key. Then you can go over the list of values in this dictionary, and update the value to be the most frequent item in the list using Counter.most_common

from collections import defaultdict, Counter

array_1 = [0,0,0,1,2,3]
array_2 = [4,4,5,6,8,7]

mapping = defaultdict(list)

#Create the mapping with a list of values
for key, value in zip(array_1, array_2):
    mapping[key].append(value)

print(mapping)
#defaultdict(<class 'list'>, {0: [4, 4, 5], 1: [6], 2: [8], 3: [7]})

res = defaultdict(int)

#Iterate over mapping and chose the most frequent element in the list, and make it the value
for key, value in mapping.items():
    #The most frequent element will be the first element of Counter.most_common
    res[key] = Counter(value).most_common(1)[0][0]

print(dict(res))

The output will be

{0: 4, 1: 6, 2: 8, 3: 7}

You can count frequencies of all mappings using Counter and then sort those mappings by key and frequency:

from collections import Counter

array_1 = [0,0,0,1,2,3]
array_2 = [4,4,5,6,8,7]
c = Counter(zip(array_1, array_2))
dict(i for i, _ in sorted(c.items(), key=lambda x: (x[0], x[1]), reverse=True))
# {3: 7, 2: 8, 1: 6, 0: 4}
Related