Making a dict from two lists/tuples

John Carter jnc at ecs.soton.ac.uk
Thu May 24 11:31:11 EDT 2001


On 24 May 2001 10:21:40 +0100, Andrew Stribblehill
<a.d.stribblehill at durham.ac.uk> wrote:

>
>I want a neat way to turn
>
>keys = ('foo', 'bar')
>values = (1, 2)
>
>into
>
>dict = {'foo': 1, 'bar': 2}.
>
>
>I'm sure there's some (possibly-functional) idiom to do this in one
>simple line, but I'm totally unable to work out what!
>
>I would append my present solution but it's embarassing.
>
>-- 
>Andrew Stribblehill
>Systems programmer, IT Service, University of Durham, England


How about this

result = [{keys[i]: values[i]} for i in range(len(keys))]

though I think that resorting to range isnt very elegant.

So try this one instead

result = [{k: v} for k, v in zip(keys, values)]

No pre initialisation of the dictionary, no for loop and all on one
line

List Comprehensions rule ok

John Carter



More information about the Python-list mailing list