Applying list values to a list of dictionaries

Viewed 61

Let's say I have a list of dictionaries that look like this:

final_list = [{'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}]

And I have a list of lists that looks like this:

input_list = [['London', 'New York', 'San Francisco'], [8908081, 8398748, 883305]]

I'm trying to map the proper values from input_list to final_list, but I can't figure out how. I'd imagine it would be something like:

n = 0 
while n < len(final_list):
     for category in input_list:
          for section in final_list:
                # then here, somehow say 
                # for the nth item in each of the sections, update the value to nth item in category
                # then increment n

Any help would be much appreciated! Thanks in advance :)

2 Answers

Here is a possible solution:

final_list = [{'city': c, 'population': p} for c, p in zip(*input_list)]

Here is the content of final_list:

[{'city': 'London', 'population': 8908081},
 {'city': 'New York', 'population': 8398748},
 {'city': 'San Francisco', 'population': 883305}]

You can do even something fancier by only using a function-based approach. This works with any number of keys you might need.

from itertools import cycle

keys = ('city', 'population')
final_list = list(map(dict, zip(cycle([keys]), zip(*input_list))))

Riccardo Bucco's solution will work, but if you want it to work with any categories (and not only city and population) this code will do it:

final_list = [{'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}]

input_list = [['London', 'New York', 'San Francisco'], [8908081, 8398748, 883305]]

for i in range(len(final_list)):
  for k in range(len(list(final_list[i].keys()))):
    final_list[i][list(final_list[i].keys())[k]] = input_list[k][i]

print(final_list)
Related