Mr ABDULLAH
Mr ABDULLAH

Reputation: 29

Preserving order of the keys while iterating over a subset of a dictionary

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

Upvotes: 2

Views: 61

Answers (1)

mozway
mozway

Reputation: 260490

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')

Upvotes: 1

Related Questions