Its Fragilis
Its Fragilis

Reputation: 208

Converting a nested list into a dictionary

I have look up several solutions, but all of them involve using numpy and complex codes, i am still a beginner and have not learned about this yet . Can anyone please offer an easier solution (i.e using a loop) on how to convert a nested list into a dictionary. The example question and the code i have tried is below:

Convert the original list into a dictionary such that the keys for each sublist are: “power1”, #“power2”, “power3”, “power4”, “power5” in that order.

I have tried doing the following code, however it only prints the last inner list:

{'powers1': [1, 32], 'powers2': [1, 32], 'powers3': [1, 32], 'powers4': [1, 32], 'powers5': [1, 32]}

This is the code that i have tried:

powers = [ [1, 2, 3, 4, 5, 6], [1, 4, 9, 16, 25], [1, 8, 27, 64], [1, 16, 81], [1, 32]] #this is the original list

powers_dictionary = {}
list_powers=["powers1","powers2","powers3","powers4","powers5"]

for ele in powers: 
  for i in list_powers:
    powers_dictionary.update({i:ele})

print(powers_dictionary)

Upvotes: 2

Views: 87

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195603

Another version, using explicite loops:

powers_dictionary = {}

list_powers=["powers1","powers2","powers3","powers4","powers5"]
powers = [ [1, 2, 3, 4, 5, 6], [1, 4, 9, 16, 25], [1, 8, 27, 64], [1, 16, 81], [1, 32]] #this is the original list

for idx, power in enumerate(list_powers):
    powers_dictionary[power] = []
    for p in powers[idx]:
        powers_dictionary[power].append(p)

print(powers_dictionary)

Prints:

{'powers1': [1, 2, 3, 4, 5, 6], 'powers2': [1, 4, 9, 16, 25], 'powers3': [1, 8, 27, 64], 'powers4': [1, 16, 81], 'powers5': [1, 32]}

Note: Using dict() with zip() is more efficient and concise.

Upvotes: 1

David Collins
David Collins

Reputation: 900

Try this:

keys = ["powers1","powers2","powers3","powers4","powers5"]
values = [ [1, 2, 3, 4, 5, 6], [1, 4, 9, 16, 25], [1, 8, 27, 64], [1, 16, 81], [1, 32]]
dictionary = dict(zip(keys, values))

Upvotes: 0

Related Questions