Click here to Skip to main content
15,889,810 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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()

but please help me understand this: - removeKeys
Posted
Updated 12-Nov-22 21:27pm

 
Share this answer
 
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.
 
Share this answer
 
v2
Comments
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.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900