NorthSide
NorthSide

Reputation: 1499

Python Dictionary - Find min key where value is equal to

I have a dictionary I would like to find the minimum key where value[1] is equal to a a specified string.

somedict = {'1': ['110', 'A'], '3': ['1', 'A'], '2': ['3', 'B'], '4': ['1', 'B']}
mindict = min(somedict.iteritems(), key=itemgetter(0) )

This gives me ('1', ['110', 'A'])

I would like to further filter this by finding the min key where value is 'B'

to give me the result ('2', ['3', 'B'])

How would go about this?

Upvotes: 2

Views: 367

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121624

Use a generator expression filtering your items first:

min((i for i in somedict.iteritems() if i[1][-1] == 'B'), key=itemgetter(0))

The generator expression produces elements from somedict.iteritems() where the last entry in the value is equal to 'B'.

Note that there is a risk here that no items match your filter! If that could be the case, make sure you catch the ValueError thrown by min() when passed an empty sequence. If you are using Python 3.4 or newer, you can specify a default to be returned for that case:

min((i for i in somedict.iteritems() if i[1][-1] == 'B'),
    key=itemgetter(0), default=())

which would return an empty tuple if no items have a last entry 'B' in their value.

Demo:

>>> from operator import itemgetter
>>> somedict = {'1': ['110', 'A'], '3': ['1', 'A'], '2': ['3', 'B'], '4': ['1', 'B']}
>>> min((i for i in somedict.iteritems() if i[1][-1] == 'B'), key=itemgetter(0))
('2', ['3', 'B'])

Upvotes: 4

Related Questions