dictionary keys() and values() relationship

Question:

I have some dictionary d.

k = d.keys()
v = d.values()

Is there a guarantee that k[n] and v[n] are related, for every n?

Asked By: Tony Ennis

||

Answers:

According to this answer on a related question, dictionaries maintain insertion order as of Python 3.6. Here is a link to Guido’s decree to "make it so".

Here is an example I did in the Python3 console to test that the relationship for every n is related:

>>> a = dict()
>>> a['yes'] = 'no'
>>> a['blah'] = 'beeper'
>>> a['foo'] = 'bar'
>>> a.keys()
dict_keys(['yes', 'blah', 'foo'])
>>> a.values()
dict_values(['no', 'beeper', 'bar'])
>>>

Edit: After reading some of the comments above, you would need to make these into lists to access them as indexes. So following that from the previous example:

>>> keys = list(a.keys())
>>> keys
['yes', 'blah', 'foo']
>>> values = list(a.values())
>>> values
['no', 'beeper', 'bar']
Answered By: Milo Fultz

Yes. Corresponding entries from .keys() and .values() represent the same key/value pair within the dictionary. (In older versions of Python, the orders may vary if you add or remove items, but they correspond if no such modifications are made between calls.)

d = {"answer": 42, "unlucky": 13, ...}
assert list(d.items()) == list(zip(d.keys(), d.values()))

This was made explicit in previous versions of the Python documentation. In recent versions of Python, where items retain their insertion order regardless of changes to the dictionary, they apparently didn’t feel it needed to be made explicit, but it’s still true.

Python dictionary: are keys() and values() always the same order?

Answered By: kindall
a = dict()
a["sas"] = 10
a["ase"] = 90
a["ing"] = 98
print(a)

And the keys on its own!

print(a[0])
print(a[1])
print(a[2])
Answered By: gz200
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.