Mostly Linux & Python syntax notes and hyperlinks.

Friday, January 8, 2010

python: mapping one list to another

I have two lists of strings. I want to associate the names of the first list with the values in the second.
Trying to do it with the mapping or dictionary type:
>>> x=['a','b']
>>> x
['a', 'b']
>>> y=['c','d']
>>> z={}
>>> z.fromkeys(x,y)
{'a': ['c', 'd'], 'b': ['c', 'd']}
That's not what I want..  Instead:
>>> d=dict(zip(x,y))
>>> d
{'a': 'c', 'b': 'd'}
>>>
That's as close as I can get it.
>>> d['a']
'c'
>>> d['b']
'd'
It seems awkward, but if you put it in a loop, it looks fine:
 >>> x=['a','b','c','d','e']
>>> y=['q','r','s','t','u']
>>> z=zip(x,y)
>>> z
[('a', 'q'), ('b', 'r'), ('c', 's'), ('d', 't'), ('e', 'u')]
>>> d=dict(z)
>>> d
{'a': 'q', 'c': 's', 'b': 'r', 'e': 'u', 'd': 't'}
>>> for key in x:
...   print key, "=", d[key]
...
a = q
b = r
c = s
d = t
e = u
>>>

No comments:

Post a Comment