Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use dictionary comprehension to combine two lists into a nested dictionary?

I want to combine the following lists into a nested dictionary using list comprehension.

dates = ['2023-04-01', '2023-04-07', '2023-04-17', '2023-04-19', '2023-04-25']
events_name = [
    'PyTexas', 'PyCamp Spain', 'PyData Berlin', 'PyCon US', 'PyLadies Amsterdam']

The dictionary should look like this:

python_events = {
    0: {'time': '2023-04-01', 'name': 'PyTexas'}, 
    1: {'time': '2023-04-07', 'name': 'PyCamp Spain'},
    2: {'time': '2023-04-17', 'name': 'PyData Berlin'},
    3: {'time': '2023-04-19', 'name': 'PyCon US'},
    4: {'time': '2023-04-25', 'name': 'PyLadies Amsterdam'}}

I am trying to use dictonary comprehension mostly for learning and practice. It seems like a bad use case for comprehension since it most likely will not be readable at all, or at least doesn’t seem like it to me

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My original way of creating the dict was looping through a range:

for i in range(0, len(dates)):
    python_events[i] = {"time": dates[i], "name": events_name[i]}

Even after some research, and using comprehension for non nested dicts, I never managed to get valid code for my comprehension. I tried multiple variants of this:

python_events = {
    i: {"time": date, "name": name for date, name in dict(foo).items()}
    for i, date, name in range(0, len(events))}

I’m clearly missing some fundamental knowledge here, so any help on how to do this would be much appreciated.

>Solution :

Yes, you can use a dict comprehension to make python_events like this:

dates = ['2023-04-01', '2023-04-07', '2023-04-17', '2023-04-19', '2023-04-25']
events_name = ['PyTexas', 'PyCamp Spain', 'PyData Berlin', 'PyCon US', 'PyLadies Amsterdam']


python_events = {i:{"time": date,"name": name } for i, (date, name) in enumerate(zip(dates,events_name))}
print(python_events)

Output as requested.

This code uses zip to iterate through your two lists at the same time and also enumerate to generate the index i.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading