Search code examples
pythonlist-comprehensiondictionary-comprehension

Applying list values to a list of dictionaries


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 :)


Solution

  • 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))))