2

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

3 Answers 3

3

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']
Sign up to request clarification or add additional context in comments.

Comments

2
>>> 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']

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.