Novice Question: two lists -> dictionary

Quinn Dunkan quinn at necro.ugcs.caltech.edu
Wed Apr 14 23:56:51 EDT 1999


On Thu, 15 Apr 1999 02:31:27 GMT, jwtozer at my-dejanews.com
<jwtozer at my-dejanews.com> wrote:
>How do I make the members of one list the key of a dictionary and the members
>of a second list the members of list values associated with with those keys?
>
>Given:
>
>ListA = ['10', '10', '20', '20', '20', '24']
>ListB = ['23', '44', '11', '19', '57', '3']
>
>Desired Result:
>
>Dict = {'10': ['23','44'],'20': ['11','19','57'], '24': ['3']}
>
>Any help will be much appreciated.

d = {}
for a, b in map(None, ListA, ListB):
	if not d.has_key(a):
		d[a] = [b]
	else:
		d[a].append(b)

Notice that python does elementary pattern-matching (and calls it "tuple
unpacking").  You can actually do nested pattern-matching like:

lst1 = (
	(1, 2),
	(3, 4),
)
lst2 = ('a', 'b')
for (a, b), c in map(None, lst1, lst2):
	print a, b, c

Also, if you have mxTools, you can do:

import NewBuiltins
d = dict(map(None, ListA, ListB))

Actually, this will give you {10: 44, 20: 57, 24: 3}, which is not what you
want, but it should be faster :)


I find the above map(None, ...) idiom useful for iterating over multiple
sequences at the same time (like haskell's zip function).  I bring up
pattern-matching because it seems to be an area of python which is not
extensively discussed in the documentation. (?)




More information about the Python-list mailing list