0

So let's say I have the following dictionary:

dic = {'a':3, 'b':2, 'c':1, 'd':1}

So I want to pop (or any other method, that remove and return) 'd' because it is the lowest Value and the right most item (in case 2 keys have the same value), values will always be ints.

I tried:

dic.popItem()

But I'm just getting a random item back, any ideas?

Also tried:

temp = min(dic.values)
del dic[temp]

But again, it's not working!

mdml
  • 22,442
  • 8
  • 58
  • 66
user2918984
  • 121
  • 4
  • 13
  • 2
    The rightmost-ness of `d` is lost as soon as it is inserted into the dictionar. The best you can do is remove _one of_ the lowest-value entries. – Robᵩ Jan 02 '14 at 17:09

2 Answers2

6

There's no such thing as the right-most item, because dictionaries are unordered.

You can delete one of the lowest-value items like this:

item = min(dic, key=dic.get)
del dic[item]
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

You need an ordereddict to get a consistent result.

See this post:

Sort a Python dictionary by value

Community
  • 1
  • 1