Entry
Converting two lists to dictionary
Converting two lists to dictionary
Jul 5th, 2000 10:03
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 364, Quinn Dunkan
"""
Packages: basic_datatypes.lists;basic_datatypes.dictionaries
"""
"""
On Thu, 15 Apr 2021 02:31:27 GMT, jwtozer@my-dejanews.com
<jwtozer@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.
"""
# [PSST] Copied for good measure
ListA = ['10', '10', '20', '20', '20', '24']
ListB = ['23', '44', '11', '19', '57', '3']
d = {}
for a, b in map(None, ListA, ListB):
if not d.has_key(a):
d[a] = [b]
else:
d[a].append(b)
print d
"""
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. (?)
"""