Mailing List Archive

Novice Question: two lists -> dictionary
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.


-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/ Search, Read, Discuss, or Start Your Own
Novice Question: two lists -> dictionary [ In reply to ]
On Thu, 15 Apr, 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.

Just off the top of my head, (after some playing around, cause
it's sooo easy to do with Python. :)

Dict = {}
for i in range(len(ListA)):
try:
Dict[ListA[i]].append(ListB[i])
except KeyError:
Dict[ListA[i]] = [ListB[i]]

This gives us
Dict = {'24': ['3'], '10': ['23', '44'], '20': ['11', '19', '57']}

I think you could write a sort function of some sort if you really
needed to get the elements in order, but it would probably just
be easier to use:

x = Dict.keys()
x.sort()
for i in x:
print i, "=", Dict[i]

And I'm sure there's an easier way to do it, as well as a way involving
map and or reduce, but it's been a while since I've programmed
functionally, so I'm not going to try.

# ignore the following code.
def myfunc( key, value ):
global Dict
try:
Dict[key].append(value)
return "got it"
except KeyError:
Dict[key] = [value]
return "need it"
map( myfunc, ListA, ListB )

Hope this helps,
Blake.

--
I speak for PCDocs
http://www.cluetrain.com/
Novice Question: two lists -> dictionary [ In reply to ]
On Thu, 15 Apr 1999 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.

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. (?)
Novice Question: two lists -> dictionary [ In reply to ]
You could do something like

**************************************************
ListA = ['10', '10', '20', '20', '20', '24']
ListB = ['23', '44', '11', '19', '57', '3']

Dict = {}
for (key, value) in map (None, ListA, ListB):
Dict [key] = Dict.get (key, [])
Dict [key].append (value)

print Dict
**************************************************

The result is

{'24': ['3'], '10': ['23', '44'], '20': ['11', '19', '57']}

See you.
Alex.
Novice Question: two lists -> dictionary [ In reply to ]
Here's a way using functional programming that also seems to work. It's
rather horrible, though.

Dict = {}
map (operator.setitem, len (ListA) * [Dict], ListA, \
map (copy.copy, len (ListA) * [[]]))
map (apply, map (getattr, map (operator.getitem, \
len (ListA) * [Dict], ListA), \
len (ListA) * ['append']), \
map (tuple, ListB))

print Dict

Alex.
Novice Question: two lists -> dictionary [ In reply to ]
Here is a quick and dirty answer! Sorry...

ListA = ['10', '10', '20', '20', '20', '24']
ListB = ['23', '44', '11', '19', '57', '3']

ListT = [] # temporary list
Dict = {}

for i in range(len(ListA)):
ListT = key_values(i, ListA, ListB)
if (Dict.has_key(ListT[0]) == 0):
Dict[ListT[0]] = ListT[1:]

print Dict # print results, for test purposes.


def key_values(i, l_key, l_val):
" returns a list with the first item being the l_key[i] (ListA),
" and the values after for that key (ListB)
resultat = []
for j in range(len(l_key)):
if (l_key[j] == l_key[i]):
result[0] = l_key[i]
result.append(l_val[j])

return result

regards,
frederic

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.
>
> -----------== Posted via Deja News, The Discussion Network ==----------
> http://www.dejanews.com/ Search, Read, Discuss, or Start Your Own
Novice Question: two lists -> dictionary [ In reply to ]
Thanks to Blake Winton, Quinn Dunkan, frederic pinel, and Alex for your
timely and useful help. What my associates Visual Basic/Access application
produced in hours, my little Python script produces in seconds.

Jeff




In article <etdd815x3s7.fsf@m2-225-12.mit.edu>,
Alex <alex@somewhere.round.here> wrote:
>
> You could do something like
>
> **************************************************
> ListA = ['10', '10', '20', '20', '20', '24']
> ListB = ['23', '44', '11', '19', '57', '3']
>
> Dict = {}
> for (key, value) in map (None, ListA, ListB):
> Dict [key] = Dict.get (key, [])
> Dict [key].append (value)
>
> print Dict
> **************************************************
>
> The result is
>
> {'24': ['3'], '10': ['23', '44'], '20': ['11', '19', '57']}
>
> See you.
> Alex.
>

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/ Search, Read, Discuss, or Start Your Own