1

This is part of my code, and I want to ask how to convert this part into dictionary way, and the result will be the same indeed. Thanks a lot!

def count_weekday(weekdays):
    weekdays_counter = [0] * 7
    for weekday in weekdays:
        if weekday == "Mon":
            weekdays_counter[0] = weekdays_counter[0] + 1
        elif weekday == "Tue":
            weekdays_counter[1] = weekdays_counter[1] + 1
        elif weekday == "Wed":
            weekdays_counter[2] = weekdays_counter[2] + 1
        elif weekday == "Thu":
            weekdays_counter[3] = weekdays_counter[3] + 1
        elif weekday == "Fri":
            weekdays_counter[4] = weekdays_counter[4] + 1
        elif weekday == "Sat":
            weekdays_counter[5] = weekdays_counter[5] + 1
        elif weekday == "Sun":
            weekdays_counter[6] = weekdays_counter[6] + 1
    return weekdays_counter
Megan
  • 541
  • 1
  • 3
  • 14
  • Does this answer your question? [How can I count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item) – Chris Nov 09 '21 at 13:49
  • HEY I CAN'T UNDERSTAND WHAT IS DICTIONARY WAY ...are you saying to make a dict that will hold values with day and there occurrence like dict={'mon':2}..something like this? – loopassembly Nov 09 '21 at 13:55

2 Answers2

2

Use dictionary comprehension:

def count_weekday(weekdays):
    return {d: weekdays.count(d) for d in ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]}

>>> count_weekday(["Sun", "Mon", "Tue", "Wed", "Thu", "Sun", "Wed", "Wed"])
{'Mon': 1, 'Tue': 1, 'Wed': 3, 'Thu': 1, 'Fri': 0, 'Sat': 0, 'Sun': 2}
not_speshal
  • 22,093
  • 2
  • 15
  • 30
2

Using collections.Counter to get the counts and operator.itemgetter to limit the counts:

from collections import Counter
from operator import itemgetter

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
get_days = itemgetter(*days)

def count_weekday(weekdays):
    return dict(zip(days, get_days(Counter(weekdays))))

Example:

>>> count_weekday(['Mon', 'foo' , 'Mon', 'Sat'])
{'Mon': 2, 'Tue': 0, 'Wed': 0, 'Thu': 0, 'Fri': 0, 'Sat': 1, 'Sun': 0}
Jab
  • 26,853
  • 21
  • 75
  • 114
  • Wow! Thank you~ "Counter" function is so useful! Thanks for your help – Megan Nov 09 '21 at 14:16
  • By the way, does "*days" means to add counts into get_days variable? – Megan Nov 09 '21 at 14:20
  • `days` is only the strings you are looking to count. The `itemgetter` is what pulls the keys. it's like using `my_dict['Mon']` for all values given to `itemgetter`. This works because `Counter` acts like a `defaultdict` where if you access a key it doesn't have populated yet it returns `0` – Jab Nov 09 '21 at 14:27