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 iterate over loist to make its values as my nested dict in python

I am not moving forward and need som help (I’m new to coding)

I have the following structure:

sim = {'S1': {}, 'S2': {}, 'S3': {}, 'S4': {}, 'S5': {}}

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

and a list
sim_list = [1,2,3,4,5]

my result should look like this:

sim = {'S1': {"number": 1}, 'S2': {"number": 2}, 'S3': {"number": 3}, 'S4': {"number": 4}, 'S5': {"number": 5}}

my attempt:

for key in sim.keys():
    for i in sim_list:
        sim[key]= {"number":i}

but i only get inner dicts with {"number":5}:

sim = {'S1': {"number": 5}, 'S2': {"number": 5}, 'S3': {"number": 5}, 'S4': {"number": 5}, 'S5': {"number": 5}}

so how can i iterate over the list objects to go to their respective place?

>Solution :

Using dict comprehension:

sim = {'S1': {}, 'S2': {}, 'S3': {}, 'S4': {}, 'S5': {}}
sim_list = [1, 2, 3, 4, 5]

output = {list(sim)[i]: {"number": sim_list[i]} for i in range(len(sim))}
print(output)

The equivalent without dict comprehension would be:

output = {}
for i in range(len(sim)):
    output[list(sim)[i]] = {"number": sim_list[i] }
print(output)

It is also possible to use zip(), to associate each key and item together:

for key, num in zip(sim.keys(), sim_list):
    sim[key] = {"number": num}
print(sim)
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