Luca
Luca

Reputation: 10996

python change value of a dictionary based on majority

I have a dictionary which has the following structure:

d = dict()
d[1] = [["car", 100, 23, 35], ["car", 101, 55, 67], ["bus", 111, 98, 99]]
d[2] = [["bus", xxx, xx, xx], ["car", 101, xx, xx], ["bus", xxx, xx, xx]]
...

Now what I want to do is change the first element of the value for each key to be the majority class for that key. For example, for item with key 1, the majority class is "car" as that occurs twice and "bus" occurs just once.

For key 2, the majority class is "bus". So, after the post processing, the dictionary should look like:

d[1] = [["car", 100, 23, 35], ["car", 101, 55, 67], ["car", 111, 98, 99]]
d[2] = [["bus", xxx, xx, xx], ["bus", 101, xx, xx], ["bus", xxx, xx, xx]]

Is there some pythonic way to do this? I was thinking of looping through all the values for all key, collect the values in a list, find the max occurrence and then again iterate and update the values but it seems a bit ugly.

Wondering if there is a concise way to express this?

Upvotes: 3

Views: 109

Answers (1)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24153

Using collections.Counter:

>>> from collections import Counter
>>> for key, values in d.items():
...     counter = Counter(value[0] for value in values)
...     majority = counter.most_common(1)[0]
...     for value in values:
...         value[0] = majority

Upvotes: 5

Related Questions