How to delete an entry from a dictionary in Python?

Python delete entry from dictionary by value

  • I am trying to delete unwanted entries from a dictionary. The dictionary looks like: { "Id":101119 ,"entry1":50009987 ,"entry2":8 ,"entry3":4 } and my code is: import json value = 2 with open(path, 'r') as json_input: unfiltered = json.load(json_input) for row in unfiltered: id = row['Id'] if row[field] is None: del output[id] elif int(row[field]) != value: del output[id] However, I've got an error: KeyError: 101119 How can I fix it? Many thanks.

  • Answer:

    You can't delete a key-value pair from a dictionary if you only know its value. One possible alternative is to create a new dictionary from the old one, filtering out the values you don't want. Example: d = {4: 8, 15: 16, 23: 42, 99: 8} d = {key: value for key, value in d.items() if value != 8} print(d) Result: {15: 16, 23: 42} I don't 100% understand your code sample, but I expect you could do: output = {key: value for key, value in output.items() if value != id}

ChangeMyName at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.