Home > Mobile >  How to prevent Python dictionary key ordering reversal?
How to prevent Python dictionary key ordering reversal?

Time:11-16

I have the following python code snippet involving dictionary,

    sample_dict = {
        "name": "Kelly",
        "age": 25,
        "salary": 8000,
        "city": "New york"
    }
    keys = ["name", "salary"]
    sample_dict = {k: sample_dict[k] for k in sample_dict.keys() - keys}
    print(sample_dict)

Why the output is {'city': 'New york', 'age': 25} and not {'age': 25, 'city': 'New york'}?

What causes the reverse ordering of dictionary keys? Any help will be highly appreciated. I executed the code on Spyder and Python 3.8.5 version.

CodePudding user response:

I guess the order is lost during processing of - between your keys() and your keys list (because it involves conversion to sets which are unordered). You can build your comprehension as follow to prevent it.

keys = {"name", "salary"}
sample_dict = {k: sample_dict[k] for k in sample_dict.keys() if k not in keys}

CodePudding user response:

@Tranbi has provided the solution to the OP. I just supplement some materials.

Although dict preserves insertion order since 3.7.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

set does not.

Being an unordered collection, sets do not record element position or order of insertion.

If you check the result of sample_dict.keys() - keys, you will find it is a set.

remain_keys = sample_dict.keys() - keys
print(type(remain_keys))
# set
for k in remain_keys:
    print(k)
# city
# age

Because dict.keys() returns a set-like view.

Keys views are set-like since their entries are unique and hashable. ... For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

  • Related