-1

I have this

my_dict = {'x':500, 'y':500, 'z': 500}
min_s=min(my_dict, key=my_dict.get)

when I print the min_s, it arbitrary print either x or y or z, but I want to just print the first key meaning x. How can I do this?

Also, how can I check if all values are the same ?

Thanks

sara jones
  • 135
  • 1
  • 9
  • Dicts are unordered in something vresions of python, which are you using? – user3483203 Apr 20 '18 at 20:48
  • You want the first key in alphabetic order or in the order you add them to the dict? Take a look at the [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict) – TwistedSim Apr 20 '18 at 20:48
  • in the same way that I add them to the dictionary – sara jones Apr 20 '18 at 20:57
  • Hi, I see you're new to SO. If you feel an answer solved the problem, please [mark it as 'accepted’](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) by clicking the green check mark. This helps keep the focus on older SO which still don't have answers. – fferri May 01 '18 at 18:35

2 Answers2

1

Dictionaries in python are not (insertion) ordered, the order will basically follow whatever hash function the dictionary is using for your keys, and that can change everytime.

For (insertion) order preserving dictionaries you should use collections.OrderedDict, see the docs for more details: https://docs.python.org/2/library/collections.html#collections.OrderedDict

EDIT However, for Python 3.6+ dicts will be insertion ordered. See this SO discussion for more details, or read the related PEP 468

WillMonge
  • 1,005
  • 8
  • 19
0

Use OrderedDict to retain the insertion order:

from collections import OrderedDict
my_dict = OrderedDict(x=500, y=500, z=500)
min_s = min(my_dict) # 'x'

You can check that all values are the same by creating a set with the dict values and checking its length:

>>> len(set(my_dict.values())) == 1
True
fferri
  • 18,285
  • 5
  • 46
  • 95