2

I am trying to remove keys from a dictionary:

incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
non_citric = {k: incomes[k] for k in incomes.keys() - {'orange'} }
non_citric

output:

{'banana': 5000.0, 'apple': 5600.0}

I am however confused as to why the original order of the keys is not preserved

mozway
  • 194,879
  • 13
  • 39
  • 75
  • 1
    The problem is unclear, what did you expect? This result is quite logic. – mozway Jan 06 '22 at 10:42
  • 4
    Orders aren't maintained for sets :) – Tsubasa Jan 06 '22 at 10:45
  • 2
    Which python version are you using? – Akshay Sehgal Jan 06 '22 at 10:45
  • 2
    As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior). So this behavior is highly likely if you are using an older version of python. Moreover, `dict` is not the right data structure to use if maintaining order is your goal. https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6 – Akshay Sehgal Jan 06 '22 at 10:47
  • see also this answer: https://stackoverflow.com/questions/1867861/how-to-keep-keys-values-in-same-order-as-declared – chenjesu Jan 06 '22 at 10:47
  • 1
    @AkshaySehgal the set created by `incomes.keys() - {'orange'}` must be ordered correctly, too. Why isn't guranteed, even in 3.6+. – timgeb Jan 06 '22 at 10:49

1 Answers1

1

IIUC, you want to remove one (or several) keys while maintaining the original order of the keys.

Then you could modify your code to:

incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
non_citric = {k: incomes[k] for k in incomes if k not in {'orange'}}
# or
# non_citric = {k: v for k,v in incomes.items() if k not in  {'orange'}}
non_citric

Why did it fail? When you run incomes.keys() - {'orange'}, the output {'apple', 'banana'} is a set, that is unordered.

In your particular case, you could also use:

non_citric = incomes.copy()
non_citric.pop('orange')
mozway
  • 194,879
  • 13
  • 39
  • 75