Skip to main content
Remove incorrect answer (doesn't work if `'key'` points to a falsy value) and explain second answer.
Source Link
user3064538
user3064538

UseYou can use a dictionary comprehension to create a new dictionary with that key removed:

>>> if myDict.get(key):my_dict myDict.pop(key)

Another way:

>>>= {k: v for k, v in myDictmy_dict.items() if k != 'key'}

You can delete by conditions. No error if key doesn't exist.

Use:

>>> if myDict.get(key): myDict.pop(key)

Another way:

>>> {k:v for k, v in myDict.items() if k != 'key'}

You can delete by conditions. No error if key doesn't exist.

You can use a dictionary comprehension to create a new dictionary with that key removed:

>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}

You can delete by conditions. No error if key doesn't exist.

Active reading.
Source Link
Peter Mortensen
  • 31.4k
  • 22
  • 110
  • 134

Use:

>>> if myDict.get(key): myDict.pop(key)


Another Another way:

>>> {k:v for k, v in myDict.items() if k !='key'= 'key'}

You can delete by conditions. No No error if keykey doesn't exist.

>>> if myDict.get(key): myDict.pop(key)


Another way

>>> {k:v for k, v in myDict.items() if k!='key'}

You can delete by conditions. No error if key doesn't exist

Use:

>>> if myDict.get(key): myDict.pop(key)

Another way:

>>> {k:v for k, v in myDict.items() if k != 'key'}

You can delete by conditions. No error if key doesn't exist.

Replaced has_key by get
Source Link
Shameem
  • 2.8k
  • 20
  • 21
>>> if myDict.has_keyget(key): myDict.pop(key)


Another way

>>> {k:v for k, v in myDict.items() if k!='key'}

You can delete by conditions. No error if key doesn't exist

>>> if myDict.has_key(key): myDict.pop(key)


Another way

>>> {k:v for k, v in myDict.items() if k!='key'}

You can delete by conditions. No error if key doesn't exist

>>> if myDict.get(key): myDict.pop(key)


Another way

>>> {k:v for k, v in myDict.items() if k!='key'}

You can delete by conditions. No error if key doesn't exist

added 56 characters in body
Source Link
Shameem
  • 2.8k
  • 20
  • 21
Loading
Source Link
Shameem
  • 2.8k
  • 20
  • 21
Loading