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
Related Q & A:
- How To Download English To Tamil Dictionary For Free?Best solution by itunes.apple.com
- How to find the index of value in python list?Best solution by Stack Overflow
- How do you store a dictionary on Parse using swift?Best solution by stackoverflow.com
- How do I delete an incorrect entry from the address book?Best solution by Yahoo! Answers
- Can I modify the keys in a dictionary directly for Python?Best solution by stackoverflow.com
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.