Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map two lists into one single list of dictionaries

Imagine I have these python lists:

keys = ['name', 'age']
values = ['Monty', 42, 'Matt', 28, 'Frank', 33]

Is there a direct or at least a simple way to produce the following list of dictionaries ?

[
    {'name': 'Monty', 'age': 42},
    {'name': 'Matt',  'age': 28},
    {'name': 'Frank', 'age': 33}
]
like image 435
Guido Avatar asked Oct 28 '08 19:10

Guido


3 Answers

Here is the zip way

def mapper(keys, values):
    n = len(keys)
    return [dict(zip(keys, values[i:i + n]))
            for i in range(0, len(values), n)]
like image 194
Toni Ruža Avatar answered Nov 12 '22 11:11

Toni Ruža


It's not pretty but here's a one-liner using a list comprehension, zip and stepping:

[dict(zip(keys, a)) for a in zip(values[::2], values[1::2])]
like image 25
jblocksom Avatar answered Nov 12 '22 13:11

jblocksom


Dumb way, but one that comes immediately to my mind:

def fields_from_list(keys, values):
    iterator = iter(values)
    while True:
        yield dict((key, iterator.next()) for key in keys)

list(fields_from_list(keys, values)) # to produce a list.
like image 2
Cheery Avatar answered Nov 12 '22 12:11

Cheery