Making a dict from two lists/tuples

Duncan Booth duncan at
Thu May 24 12:49:52 CEST 2001

"Jonas Meyer Rasmussen" <meyer at> wrote in 
news:9eiljf$jg1$1 at

> for key,value in keys,values
>     dict[key] = value

Bzzzt! Wrong answer.

    	for key, value in zip(keys,values): dict[key] = value

or if you are still using old versions of Python:

    	for key, value in map(None, keys,values): dict[key] = value

If you want to get rid of the for loop you could do:

    	map(dict.setdefault, keys, values)

although this will have slightly different behaviour if any of the keys are 
repeated (the setdefault will use the first value found with any key, the 
assignments will overwrite and hence use the last value for a given key).

If you are likely to have multiple values with the same key you might 
    	dict = {}
    	for key,value in zip(keys,values):
    	    	dict.setdefault(key, []).append(value)
which sets each dictionary element to a list of all the relevant values.

Duncan Booth                                             duncan at
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list