-2

So i have a response from an api (openweathermap.org) and i have all the {weather} variables in a list. I am trying to get the most common in ["Sunny", "Scattered clouds", "Rainy", "Scattered Clouds"] Just an example but something like that.

I also thought of a way using for loops and dictionaries:

listt = ["R","S","SC","SC"]
dictt = {}
for i in listt:
    dict[f"{i}"] +=1

But... Yeah. I know it would not work. I mean, i could hard code dictt but i dont know all the weather conditions from the API. Is there another way to get the most common String in a list?

i am using one-call api from openweathermap.org

  • Not sure if i get i right but if you want to know which is the most occuring weather type from the list you can use collections an eg ref https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item – sb9 Jan 22 '22 at 05:29
  • 1
    You can use the `Counter` type found in the standard `collections` library. It has a method called `.most_common()` . https://docs.python.org/3/library/collections.html#counter-objects – Ederic Oytas Jan 22 '22 at 05:33
  • Please be aware that ``dict[f"{i}"]`` is just ``dict[i]``. – MisterMiyagi Jan 22 '22 at 05:36
  • This is your exact answer https://stackoverflow.com/a/59246517/13202252 – Fareed Khan Jan 22 '22 at 05:40

1 Answers1

-1

Solution

(Tested in Python 2 and 3)

You could use a dictionary to map the values like what you provided.

Then to get the key or most common string in the dictionary, get the key of the maximum value in the dictionary, like this: (Reference)

listt = ["R","S","SC","SC"]
dictt = {}

for i in listt:
    # add to dictionary if it does not exist
    if i not in dictt:
        # this also does the same thing as 'dict[f"{i}"]' 
        dictt[i] = 1

    # update dictionary
    else:
        dictt[i] +=1

print(max(dictt))
# 'SC'

Other Remarks

  • Possible duplicate as commented by @Fareed Khan
  • You can also utilize Counters in python (as commented by @Ederic Oytas)

from collections import Counter

listt = ["R","S","SC","SC"]
print(max(Counter(listt)))
# 'SC'