15,960,390 members
See more:
D = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'}
removeKeys = [0, 2, 5]

X = {k: D[k] for k in D.keys() - removeKeys}

print(X)
# Prints {1: 'B', 3: 'D', 4: 'E'}

What I have tried:

hi friend, i understand this dict comprehension: X = {k: D[k] for k in D.keys()

Posted
Updated 12-Nov-22 21:27pm

## Solution 2

Python
```D = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'}
removeKeys = [0, 2, 5]

X = {k: D[k] for k in D.keys() - removeKeys}```

The variable `removeKeys` is a simple `List`. The result of the call to `D.keys()` is another `List` actually a view of the dictionary consisting of just the key values:
Python
```keys = D.keys() # result is {0, 1, 2, 3, 4, 5}
# so
D.keys - removeKeys # gives { 1, 3, 4} --> values 0, 2 and 5 removed```

So the dictionary comprehension iterates the list { 1, 3, 4 } and creates a new dictionary using those values as the keys.

v2
Member 15829581 13-Nov-22 3:32am
i thought you cannot subtract 2 list
Richard MacCutchan 13-Nov-22 3:45am
Well, it works for me.