[Tutor] create dict from 2 lists
Tim Peters
tim.one at comcast.net
Fri Apr 2 10:57:26 EST 2004
[Cedric BRINER]:
>> assume that I want to create the dict:
>> p={1:11,2:22,3:33,4:44}
>>
>> and that i have:
>> the keys=[1,2,3,4] and
>> the values=[11,22,33,44]
>>
>> Is the simpliest way to do this, is to do :
>> p={}
>> for i in range(len(keys)):
>> p[keys[i]]=values[i]
>>
>> or is there a hidded function which do this?
[Gregor Lindl]
> You could use the non-hidden function zip:
> (See: Python Library Reference 2.1)
>
> >>> keys=[1,2,3,4]
> >>> values=[11,22,33,44]
> >>> p={}
> >>> for key,value in zip(keys,values):
> p[key]=value
>
> >>> p
> {1: 11, 2: 22, 3: 33, 4: 44}
Or print dict.__doc__, and ponder this section:
dict(seq) -> new dictionary initialized as if via:
d = {}
for k, v in seq:
d[k] = v
So this also works:
>>> keys = [1, 2, 3, 4]
>>> values = [11, 22, 33, 44]
>>> dict(zip(keys, values))
{1: 11, 2: 22, 3: 33, 4: 44}
>>>
More information about the Tutor
mailing list