Art Grc
Art Grc

Reputation: 471

grouping elements into new list from two lists using python

I have two really long lists in python, the first with words in english, and the second with spanish words. Because the second list is generated from the first list, a lot of elements are repeated, so I need a way to group those elements with the respective translation.

for example:

#my two lists
a=['car', 'house', 'wagon', 'rat', 'mouse', 'cart']
b=['carro', 'casa', 'carro', 'raton', 'raton', 'carro']
#the resulting list must be something like this
c=['car, wagon, cart: carro', 'house: casa', 'rat, mouse: raton']

thanks in advance

p.s. it's not a homework, it's a small program that I'm trying to create to learn vocabulary

Upvotes: 2

Views: 184

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

>>> dic = {}
>>> for v, k in zip(a, b):
        dic.setdefault(k, []).append(v)

>>> ["{}: {}".format(', '.join(v),k)  for k,v in dic.iteritems()]
['house: casa', 'car, wagon, cart: carro', 'rat, mouse: raton']

Upvotes: 2

jamylak
jamylak

Reputation: 133554

If order doesn't matter I would just go with this:

>>> from collections import defaultdict
>>> a=['car', 'house', 'wagon', 'rat', 'mouse', 'cart']
>>> b=['carro', 'casa', 'carro', 'raton', 'raton', 'carro']
>>> d = defaultdict(list)
>>> for k, v in zip(b, a):
        d[k].append(v)

This is what d looks like:

>>> d
defaultdict(<type 'list'>, {'casa': ['house'], 'carro': ['car', 'wagon', 'cart'], 'raton': ['rat', 'mouse']})

And to get the final result

>>> ['{0}: {1}'.format(', '.join(v), k) for k, v in d.items()]
['house: casa', 'car, wagon, cart: carro', 'rat, mouse: raton']

If order does matter, and you need that result exactly:

>>> d = OrderedDict()
>>> for k, v in zip(b, a):
        d.setdefault(k, []).append(v)


>>> ['{0}: {1}'.format(', '.join(v), k) for k, v in d.items()]
['car, wagon, cart: carro', 'house: casa', 'rat, mouse: raton']

Upvotes: 3

jedwards
jedwards

Reputation: 30210

Something like this:

#!/bin/env python

import pprint

a=['car', 'house', 'wagon', 'rat', 'mouse', 'cart']
b=['carro', 'casa', 'carro', 'raton', 'raton', 'carro']

d = {}
for pair in zip(a,b):
    if pair[1] not in d: d[pair[1]] = []
    d[pair[1]].append(pair[0])

pprint.pprint(d)

Prints:

{'carro': ['car', 'wagon', 'cart'],
 'casa': ['house'],
 'raton': ['rat', 'mouse']}

You could format it differently, just loop through the dictionary d.

Upvotes: 1

Related Questions