Search code examples
pythonlist-comprehensiondictionary-comprehension

Creating empty lists with comprehension


I would like to receive some help with this code:

from datetime import datetime

flights = {
'09:35' : 'FREEPORT',
 '09:55' : 'WEST END',
 '10:45' : 'TREASURE CAY',
 '11:45' : 'ROCK SOUND',
 '12:00' : 'TREASURE CAY',
 '17:00' : 'FREEPORT',
 '17:55' : 'ROCK SOUND',
 '19:00' : 'WEST END' }

def convert_to_ampm(time24: str) -> str:
    return datetime.strptime(time24, '%H:%M').strftime('%I:%M %p')

flights_copy = {}


for k, v in flights.items():
    if v not in flights_copy:
        flights_copy[v] = []
    flights_copy[v].append(k)


for k, v in flights_copy.items():
    time = []
    for item in v:
        time.append(convert_to_ampm((item)))
    print(k.title(), ':',time)

is there a way to make this code written in comprehension:

for k, v in flights.items():
    if v not in flights_copy:
        flights_copy[v] = []
    flights_copy[v].append(k)

I'm currently learning Python and I'm not very knowledgeable and I'm also sorry for my poor English skills. Thanks!



Solution

  • As a single comprehension, you can do it at least this way:

    from itertools import groupby
    from operator import itemgetter
    
    flights_copy = {
        v: [i[0] for i in d]
        for v, d in groupby(sorted(flights.items(), key=itemgetter(1)), itemgetter(1))
    }
    

    So if flights is: {1: 20, 2: 20, 3: 10, 4: 15} then the code above produces: {10: [3], 15: [4], 20: [1, 2]}

    However, your initial code is readable and works fine.  You could improve it a little by doing it as:

    from collections import defaultdict
    
    flights_copy = defaultdict(list)
    for k, v in flights.items():
        flights_copy[v].append(k)