So I have found the frequencies of numbers from a list and have created a list such as this [2:3 , 25:1, 22:4, 5:2, 5:2] What im trying to do after that is have a for loop detecting the maximum frequency (different numbers can have the same frequencies) and then printing the number and frequency that is the highest which may be more than one.
Asked
Active
Viewed 127 times
0
-
7Do you have a `list` or a `dict`? Because `[2:3 , 25:1, 22:4, 5:2, 5:2]` is neither. – mata May 30 '12 at 07:39
-
So, in `2:3`, which is the number and which is the frequency? Also, what is the significance of `5:2` appearing twice? – NPE May 30 '12 at 07:41
-
So number is 2 and frequency is 3. Umm trying to show that different numbers can have the same max frequency – bluelantern May 30 '12 at 07:43
-
Are you trying to do something like this? http://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary – acattle May 30 '12 at 07:44
-
My guess is for 2:3 you get the frequency when you divide 2 by 3. @bluelantem some clarification would help. What's the datatype of a single list entry? – Nicola Coretti May 30 '12 at 07:46
-
The Number is 2, the frequency is 3 – bluelantern May 30 '12 at 07:47
-
1So it's a dictionary? I.e. {2:3 , 25:1, 22:4, 5:2}? Why does 5:2 appear twice? Is this a homework assignment? – acattle May 30 '12 at 07:58
-
Yes my bad sorry a dictionary – bluelantern May 30 '12 at 08:17
1 Answers
1
Depending on how your data is structured
>>> data = {2:3 , 25:1, 22:4, 5:2, 5:2}
>>> max(data, key = lambda x: data[x])
22
or
>>> data = [(2, 3), (25, 1), (22, 4), (5,2), (5,2)]
>>> max(data, key = lambda x: x[1])
(22, 4)
should do the trick.
[Edit]
>>> data = {2:3 , 25:4, 22:4, 5:2, 5:2}
>>> max_key = max(data.values())
>>> print [i for i in data if data[i] == max_key]
[22, 25]

luke14free
- 2,529
- 1
- 17
- 25
-
Lets say you have data = {2:4, 5:4, 3:2, 22:6} how would you display 2 and 5 – bluelantern May 30 '12 at 08:24
-
1Edited, this will take into account multiple values. You are using a bad data structure though. I strongly suggest you to take a look at http://docs.python.org/dev/library/collections.html#collections.Counter – luke14free May 30 '12 at 08:29