简体   繁体   中英

Delete certain values from a dictionary?

I want to delete the keys in my dictionary with the value of 1 , but the only way I know of is to manually input keys to delete which is inefficient. Any ideas?

I have a feeling I should use:

for key,value in mydict.items():

For example, if I had the dictionary

mydict = {'a':1, 'b':2, 'c':3, 'd':1, 'e':1}

how would I delete the keys with a value of 1 so that I can print a dictionary purely of keys with values > 1 ?

You can use a dict comprehension to filter the dictionary:

>>> mydict = {'a':1, 'b':2, 'c':3, 'd':1, 'e':1}
>>> {k:v for k,v in mydict.items() if v != 1}
{'c': 3, 'b': 2}
>>>

Note that you should use mydict.iteritems() if you are on Python 2.x to avoid creating an unnecessary list.

You could go though each of the items (the key value pair) in the dictionary to check the conflict and add value in new Dict.(here.. result) that not contain duplicate.

mydict = {'a':1, 'b':2, 'c':3, 'd':1, 'e':1}
result = {}

for key,value in mydict.items():
    if value not in result.values():
        result[key] = value

print result

To create a new dictionary with the items which has the value greater than 1 use dict comprehension like below.

>>> mydict = {'a':1, 'b':2, 'c':3, 'd':1, 'e':1}
>>> {key:value for key,value in mydict.items() if value > 1}
{'c': 3, 'b': 2}

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