1

I have an array of dictionary elements like this:

d = [{'k': 'k1', 'v':4}, {'k': 'k2', 'v':5}, {'k': 'k3', 'v':2}]

I would like to retrieve a value of 'k' from the the dictionary element with lowest 'v', there may be more than one with the same lowest value. In the case of the example above, I would like to get:

['k3']

This is what what I have so far, is this the most efficient and pythonic way of solving the problem (besides collapsing the two lines into one)?

m = min([x['v'] for x in d])                               
r = [x['k'] for x in d if x['v'] == m]    

Thanks.

2
  • 2
    k3 is not one of your keys. Commented Apr 20, 2014 at 14:17
  • Sorry I was not clear - I edited to be more exact Commented Apr 20, 2014 at 14:31

2 Answers 2

2

Remove the unnecessary list comprehension and use a generator expression instead.

m = min(x['v'] for x in d)                               
r = [x['k'] for x in d if x['v'] == m]   

But is there a reason you are keeping a list of key-value pairs, rather than a dict? (To have a multimap?)

d = {'k1':4, 'k2':5, 'k3':2}
m = min(d.itervalues())                        
r = [k for k, v in d.iteritems() if v == m]   
Sign up to request clarification or add additional context in comments.

2 Comments

The list of dictionaries is what I am given to work with form another part of the system, I would like to just retrieve a value of 'k' from the the dictionary element with lowest 'v', there may be more than one with the same lowest value.
@IUnknown, if possible, if d is meant simply to be a list of keys and values, I would recommended changing that part of the system (if possible) to use a dict.
0
r = min(d, key=lambda x: x["v"])["k"]

This should give you 'k3'

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.