0

If I have a dictionary a, are a.keys() guaranteed to come in the same order as a.values()?

That is to say, is the fir element of a.keys() guaranteed to correspond to the first element of a.values(), and so on for the other elements?

Said otherwise, given:

a = {"a":1, "b":2}
b = {k:v for k,v in zip(a.keys(),a.values())}

is a==b always and guaranteed to be True?

robertspierre
  • 3,218
  • 2
  • 31
  • 46

1 Answers1

3

Yes, if no modifications are made between calling .keys() and .values(). And in fact, from Python 3.7 onwards:

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.

As stated in the official documentation.

You might be interested in the .items() method though, since it is equivalent to your zip(a.keys(),a.values()).

Miquel Escobar
  • 380
  • 1
  • 6
  • I upvoted your answer, but it would GREATLY benefit from a concise explanation and reference to the documentation. Otherwise your answer is literally just "Yes" and is not really helpful unless we blindly trust you (not to mention, if in the future someone else posts an answer with just "No" in it, we wouldn't know which of the two answers to trust). – Stef Sep 02 '21 at 16:16
  • 1
    A concise explanation is straightforward in python>=3.7 : `dict` are guaranteed to be ordered by insertion order. So, `.keys()` is guaranteed to be ordered in insertion order, and `.values()` is guaranteed to be ordered in insertion order, and `.item()` is guaranteed to be ordered in insertion order. – Stef Sep 02 '21 at 16:17
  • Edited the post to include this. – Miquel Escobar Sep 02 '21 at 16:25