简体   繁体   中英

How to remove dictionary key with known value?

Assume python dict:

mydict = {'a': 100, 'b': 200, 'c': 300}

I know one of the values:

value = 200

How to remove the 'b': 200 pair from the dict? I need this:

mydict = {'a': 100, 'c': 300}

Use a dictionary comprehension . Note that (as jonrsharpe has stated) this will create a new dictionary which excludes the key:value pair that you want to remove. If you want to delete it from your original dictionary then please see his answer.

>>> d = {'a': 100, 'b': 200, 'c': 300}
>>> val = 200
# Use d.items() for Python 2.x and d.iteritems() for Python 3.x
>>> d2 = {k:v for k,v in d.items() if v != val}
>>> d2
{'a': 100, 'c': 300}

It sounds like you want:

for key, val in list(mydict.items()):
    if val == value:
        del mydict[key]
        break # unless you want to remove multiple occurences

You'll need to loop over every items(), either with dict comprehension:

new_dict = {k:v for k,v in my_dict.items() if predicate(value)}

Or modifying the existing dictionary:

for k,v in my_dict.items():
    if not predicate(v):
        del my_dict[k]

The simplest i found:

for key in [k for k,v in mydict.items() if v==200]:
    del mydict[key]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM