0

From this source: https://www.geeksforgeeks.org/python-get-key-from-value-in-dictionary/

Was wondering why this works?

# creating a new dictionary 
my_dict ={"java":100, "python":112, "c":11} 

# list out keys and values separately 
key_list = list(my_dict.keys()) 
val_list = list(my_dict.values()) 

print(key_list[val_list.index(100)]) 
print(key_list[val_list.index(112)]) 

I understand the code, but I thought dictionaries didn't store any internal order so how/why do the .keys() and .values() method preserve order?

Newbie to python here.

Thanks!

Jamalan
  • 482
  • 4
  • 15
  • 2
    Two issues. 1) dictionaries are ordered as of Python 3.6 (implementation detail) but guaranteed in Python 3.7+. 2) `keys()` and `values()` would always give the same ordering provided that the dictionary wasn't altered between the two calls (which it isn't here), even if this ordering was not guaranteed to be the same as was used to create the dictionary https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order/835430] – roganjosh Jan 19 '20 at 21:18
  • Oh thanks for the info, can key-value pairs be referenced by index then? – Jamalan Jan 19 '20 at 22:17

1 Answers1

0

Since Python 3.6 dict has maintained order after implementation of a new compact dictionary type.

What's New in Python 3.6 -- New dict implementation

The dict type now uses a “compact” representation based on a proposal by Raymond Hettinger which was first implemented by PyPy. The memory usage of the new dict() is between 20% and 25% smaller compared to Python 3.5.

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).

As of Python 3.7 the above was no longer implementation detail, and dict maintaining order became an official language detail.

[Python-Dev] Guarantee ordered dict literals in v3.7?

Make it so. "Dict keeps insertion order" is the ruling. Thanks!

Community
  • 1
  • 1
felipe
  • 7,324
  • 2
  • 28
  • 37