简体   繁体   中英

Finding the max count of months in a list of dictionaries

I have a list of dictionaries, referenced as city_file, that include several key value pairs. I am looking to use Counter to find the most common month for the 'Start Time ' key which is provided in '2017-06-01 11:45:35' form.

How would I go about using datetime to convert the values of 'Start Time' to only return the count of months rather than the full 'Start Time' value and pass that into the Counter (ex: 2017-06-01 11:45:35 as 'January' and gives the total count of January start times).

I have this so far:

c = Counter((month['Start Time']) for month in city_file)

and it counts each value as unique values for each 'Start Time' rather than counting the number of rides in January.

input:

city_file = [
    {'Start Time': '2017-01-01 00:00:36', 'Trip Duration': '356', 'User Type': 'Customer'}, 
    {'Start Time': '2017-01-01 00:00:36', 'Trip Duration': '356', 'User Type': 'Customer'}, 
    {'Start Time': '2017-02-01 00:00:36', 'Trip Duration': '356', 'User Type': 'Customer'}
]

expected output:

[(January: 2), (February: 1)]

If you only need the month you can extract that part of the string like:

Code:

c = Counter(month['Start Time'][5:7] for month in city_file)

Test Code:

import calendar
from collections import Counter
dates = (
    '2017-05-01 11:45:35',
    '2017-06-01 11:45:35',
    '2017-06-01 11:45:35',
    '2017-07-01 11:45:35',
)
city_file = [{'Start Time': d} for d in dates]

c = Counter((calendar.month_name[int(month['Start Time'][5:7])] for month in city_file))

print(c)

Results:

Counter({'June': 2, 'May': 1, 'July': 1})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM