Removing Entries from a Dictionary Based on Values

What is the best way to remove a dictionary item by value in python?

You can use a simple dict comprehension:

myDict = {key:val for key, val in myDict.items() if val != 42}

As such:

>>> {key:val for key, val in myDict.items() if val != 42}
{8: 14, 1: 'egg'}

Removing entries from a dictionary based on values

You can use a dict comprehension:

>>> { k:v for k, v in hand.items() if v }
{'m': 1, 'l': 1}

Or, in pre-2.7 Python, the dict constructor in combination with a generator expression:

>>> dict((k, v) for k, v in hand.iteritems() if v)
{'m': 1, 'l': 1}

How do I remove all items in a dictionary with a value less than a variable?

Using a dict comprehension

Ex:

data = {"word1" : 5, "word2" : 3, "word3" : 15, "word4" : 12}
print({k:v for k, v in data.items() if v > 10})

Output:

{'word3': 15, 'word4': 12}

How to remove elements from a Python dictionary based on elements in a list?

I would use a dictionary comprehension to map the keys with the values that aren't found within a list:

new_dict = {k: v for k, v in old_dict.items() if v not in the_list} # filter from the list

Remove a dictionary key that has a certain value

Modifying the original dict:

for k,v in your_dict.items():
if v == 'DNC':
del your_dict[k]

or create a new dict using dict comprehension:

your_dict = {k:v for k,v in your_dict.items() if v != 'DNC'}

From the docs on iteritems(),iterkeys() and itervalues():

Using iteritems(), iterkeys() or itervalues() while adding or
deleting entries in the dictionary may raise a RuntimeError or fail
to iterate over all entries.

Same applies to the normal for key in dict: loop.

In Python 3 this is applicable to dict.keys(), dict.values() and dict.items().

How to remove elements from lists in dictionaries based on condition in python

You are not accessing the lists correctly. You would want to do:

del cat_map[k][cat_map[k].index(item)]

but you could simplify this check by:

for k,v in cat_map.items():
if k in v:
v.remove(k)

Removing a key in a list of dictionary with if value condition in python

you can try:

Data = [{key: value for key, value in entry.items() if value != "N/A"} for entry in Data]

deleting entries in a dictionary based on a condition

The usual way is to create a new dictionary containing only the items you want to keep:

new_data = {k: v for k, v in data.items() if v[0] <= 30}

If you need to change the original dictionary in place, you can use a for-loop:

for k, v in list(data.items()):
if v[0] > 30:
del data[k]

Note that list(data.items()) creates a shallow copy of the items of the dictionary, i.e. a new list containing references to all keys and values, so it's safe to modify the original dict inside the loop.



Related Topics



Leave a reply



Submit