Home > OS >  Order of dictionary keys when performing conditional list comprehension in Python
Order of dictionary keys when performing conditional list comprehension in Python

Time:10-07

In Python 3.10, I am aware that a dictionary preserves insertion order. However when performing conditional list comprehensions, can this order still be guaranteed?

For example, given:

my_dict = {}
my_dict['a'] = 1
my_dict['b'] = 2
my_dict['c'] = 3
my_dict['d'] = 4

Can one guarantee that either (option A):

print([k for k in my_dict.keys() if k not in ['c']])

or (option B):

print([k for k in (my_dict.keys() - {'c'})])

will always return:

['a', 'b', 'd']

CodePudding user response:

Iterating over dict or dict.keys() should give the same results for any version of Python, since the language guarantees the current order will always be stable, even if it doesn't necessarily match the insertion order. In Python 3, the keys() method provides a dynamic view of the dictionary's entries, so it will directly reflect the current state of the dict. The views themselves may be "set-like", but that does not imply they are unordered (or independently ordered).

The problem with the examples in the question is that they don't compare like with like. The keys() method returns a view (or a list in earlier versions), whereas keys() - {'a'} evaluates to a set (i.e. an object with no guaranteed order). So it is safe to assume option A will always give the same results, but not option B.

CodePudding user response:

I think the short answer is yes, the "preserves insertion order" clause gives you a proper order of keys whenever you go through them (be it via for k in my_dict or my_dict.keys()), and together with the one that @Larry pointed out gives you what you ask for.

However the downwotes on this question are probably due to the fact that if you need an answer to this question for a coding problem, you should either learn more about list comprehensions or just rethink your solution and sort the keys based on insertion order or whatever way of guaranteing you'd imagine

  • Related