Home > Enterprise >  How to convert this section(list) into dictionary?
How to convert this section(list) into dictionary?

Time:11-10

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

CodePudding user response:

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}

CodePudding user response:

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}
  • Related