Home > Blockchain >  How to iterate over loist to make its values as my nested dict in python
How to iterate over loist to make its values as my nested dict in python

Time:02-23

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': {}}

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?

CodePudding user response:

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)

CodePudding user response:

Or you could build the dictionary from scratch using a dictionary comprehension thus:

sim = {f'S{i}': {'number': i} for i in range(1, 6)}

print(sim)

Output:

{'S1': {'number': 1}, 'S2': {'number': 2}, 'S3': {'number': 3}, 'S4': {'number': 4}, 'S5': {'number': 5}}
  • Related