Merging two lists as a dictionary

Ivan Van Laningham ivanlan at callware.com
Tue Jul 20 23:35:55 EDT 1999


Hi All--

Chris Frost wrote:
> 
> I have two lists and would like to merge them into a dictionary, with one
> list forming the keywords and the other the values in the dictionary. How could
> this be done? "map(None, keyword_list, value_list)" looked great, but it
> returns a list of pairs (I'd like to be able to specify values according to
> keywords...).
> 
> thanks for any pointers!

Here's a simplistic implementation:
----------------------------------------------
#!/usr/local/bin/python

k = ["one","two","three"]
v = [1,2,3]
d = {}

n = 0
for i in k:
    d[i] = v[n]
    n = n + 1

print "Keys:", k
print "Values:", v
print "Dictionary:", d
----------------------------------------------

Alternatively, you could take the list of pairs (tuples) you get back
from map() and iterate over that:

for i in pairs:
	dict[i[0]] = i[1]

<you're-in-trouble-if-the-lists-aren't-the-same-length>-ly y'rs,
Ivan
----------------------------------------------
Ivan Van Laningham
Callware Technologies, Inc.
ivanlan at callware.com
ivanlan at home.com
http://www.pauahtun.org
See also: 
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
----------------------------------------------




More information about the Python-list mailing list