Reputation: 97
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
?
Upvotes: 0
Views: 99
Reputation: 1551
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
Upvotes: 1
Reputation: 174696
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}
Upvotes: 0
Reputation:
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.
Upvotes: 2