1

For example, I have two dictionaries:

a = {
    'Letters': ['Alpha', 'Beta', 'Theta'],
    'Animals': ['Dog', 'Cat', 'Ox']
}

I need to satisfy a condition such that I return a list so that only the values in 'Letters' that are greater than/equal to/less than (as specified) the corresponding values in 'Animals' are included.

Basically, is there a simple way to only compare the values in the list at matching indexes?

'Alpha' vs. 'Dog'

'Beta' vs. 'Cat'

'Theta' vs. 'Ox'

2 Answers 2

2

To get corresponding pairs, you can use zip (think of how a jacket zipper behaves):

>>> a = {'Letters': ['Alpha', 'Beta', 'Theta'], 'Animals': ['Dog', 'Cat', 'Ox']}
>>> zip(a["Letters"], a["Animals"])
[('Alpha', 'Dog'), ('Beta', 'Cat'), ('Theta', 'Ox')]

If you don't care about the order, only about the correspondence, you could reduce this to

>>> zip(*a.values())
[('Dog', 'Alpha'), ('Cat', 'Beta'), ('Ox', 'Theta')]

(In Python 3, make that list(zip(..)) to get a list, but you can still iterate over it, as in for pair in zip(*a.values()): print(pair), without materializing it.)

0

You could do:

>>> a = {'Letters': ['Alpha', 'Beta', 'Theta'], 'Animals': ['Dog', 'Cat', 'Ox']}
>>> [ letter for letter, animal in zip( a['Letters'], a['Animals']) if letter > animal]
['Theta']
>>> [ letter for letter, animal in zip( a['Letters'], a['Animals']) if letter < animal]
['Alpha', 'Beta']
>>>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.