removing a key from dict in Python [duplicate] - python

I want to remove a key from a dictionary if it is present. I currently use this code:
if 'key' in my_dict:
del my_dict['key']
Without the if statement, the code will raise KeyError if the key is not present. How can I handle this more simply?
See Delete an element from a dictionary for more general approaches to the problem of removing a key from a dict (including ones which produce a modified copy).

To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():
my_dict.pop('key', None)
This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.
To delete a key that is guaranteed to exist, you can also use
del my_dict['key']
This will raise a KeyError if the key is not in the dictionary.

Specifically to answer "is there a one line way of doing this?"
if 'key' in my_dict: del my_dict['key']
...well, you asked ;-)
You should consider, though, that this way of deleting an object from a dict is not atomic—it is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of
try:
del my_dict['key']
except KeyError:
pass
which, of course, is definitely not a one-liner.

It took me some time to figure out what exactly my_dict.pop("key", None) is doing. So I'll add this as an answer to save others googling time:
pop(key[, default])
If key is in the dictionary, remove it and return its value, else
return default. If default is not given and key is not in the
dictionary, a KeyError is raised.
Documentation

del my_dict[key] is slightly faster than my_dict.pop(key) for removing a key from a dictionary when the key exists
>>> import timeit
>>> setup = "d = {i: i for i in range(100000)}"
>>> timeit.timeit("del d[3]", setup=setup, number=1)
1.79e-06
>>> timeit.timeit("d.pop(3)", setup=setup, number=1)
2.09e-06
>>> timeit.timeit("d2 = {key: val for key, val in d.items() if key != 3}", setup=setup, number=1)
0.00786
But when the key doesn't exist if key in my_dict: del my_dict[key] is slightly faster than my_dict.pop(key, None). Both are at least three times faster than del in a try/except statement:
>>> timeit.timeit("if 'missing key' in d: del d['missing key']", setup=setup)
0.0229
>>> timeit.timeit("d.pop('missing key', None)", setup=setup)
0.0426
>>> try_except = """
... try:
... del d['missing key']
... except KeyError:
... pass
... """
>>> timeit.timeit(try_except, setup=setup)
0.133

If you need to remove a lot of keys from a dictionary in one line of code, I think using map() is quite succinct and Pythonic readable:
myDict = {'a':1,'b':2,'c':3,'d':4}
map(myDict.pop, ['a','c']) # The list of keys to remove
>>> myDict
{'b': 2, 'd': 4}
And if you need to catch errors where you pop a value that isn't in the dictionary, use lambda inside map() like this:
map(lambda x: myDict.pop(x,None), ['a', 'c', 'e'])
[1, 3, None] # pop returns
>>> myDict
{'b': 2, 'd': 4}
or in python3, you must use a list comprehension instead:
[myDict.pop(x, None) for x in ['a', 'c', 'e']]
It works. And 'e' did not cause an error, even though myDict did not have an 'e' key.

You can use a dictionary comprehension to create a new dictionary with that key removed:
>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}
You can delete by conditions. No error if key doesn't exist.

You can use exception handling if you want to be very verbose:
try:
del dict[key]
except KeyError: pass
This is slower, however, than the pop() method, if the key doesn't exist.
my_dict.pop('key', None)
It won't matter for a few keys, but if you're doing this repeatedly, then the latter method is a better bet.
The fastest approach is this:
if 'key' in dict:
del myDict['key']
But this method is dangerous because if 'key' is removed in between the two lines, a KeyError will be raised.

We can delete a key from a Python dictionary by the some of the following approaches.
Using the del keyword; it's almost the same approach like you did though -
myDict = {'one': 100, 'two': 200, 'three': 300 }
print(myDict) # {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : del myDict['one']
print(myDict) # {'two': 200, 'three': 300}
Or
We can do like the following:
But one should keep in mind that, in this process actually it won't delete any key from the dictionary rather than making a specific key excluded from that dictionary. In addition, I observed that it returned a dictionary which was not ordered the same as myDict.
myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
{key:value for key, value in myDict.items() if key != 'one'}
If we run it in the shell, it'll execute something like {'five': 500, 'four': 400, 'three': 300, 'two': 200} - notice that it's not the same ordered as myDict. Again if we try to print myDict, then we can see all keys including which we excluded from the dictionary by this approach. However, we can make a new dictionary by assigning the following statement into a variable:
var = {key:value for key, value in myDict.items() if key != 'one'}
Now if we try to print it, then it'll follow the parent order:
print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}
Or
Using the pop() method.
myDict = {'one': 100, 'two': 200, 'three': 300}
print(myDict)
if myDict.get('one') : myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
The difference between del and pop is that, using pop() method, we can actually store the key's value if needed, like the following:
myDict = {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : var = myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
print(var) # 100
Fork this gist for future reference, if you find this useful.

I prefer the immutable version
foo = {
1:1,
2:2,
3:3
}
removeKeys = [1,2]
def woKeys(dct, keyIter):
return {
k:v
for k,v in dct.items() if k not in keyIter
}
>>> print(woKeys(foo, removeKeys))
{3: 3}
>>> print(foo)
{1: 1, 2: 2, 3: 3}

Another way is by using items() + dict comprehension.
items() coupled with dict comprehension can also help us achieve the task of key-value pair deletion, but it has the drawback of not being an in place dict technique. Actually a new dict if created except for the key we don’t wish to include.
test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21}
# Printing dictionary before removal
print ("dictionary before performing remove is : " + str(test_dict))
# Using items() + dict comprehension to remove a dict. pair
# removes vinod
new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'}
# Printing dictionary after removal
print ("dictionary after remove is : " + str(new_dict))
Output:
dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}

Related

How do I remove a JSON element [duplicate]

I want to remove a key from a dictionary if it is present. I currently use this code:
if 'key' in my_dict:
del my_dict['key']
Without the if statement, the code will raise KeyError if the key is not present. How can I handle this more simply?
See Delete an element from a dictionary for more general approaches to the problem of removing a key from a dict (including ones which produce a modified copy).
To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():
my_dict.pop('key', None)
This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.
To delete a key that is guaranteed to exist, you can also use
del my_dict['key']
This will raise a KeyError if the key is not in the dictionary.
Specifically to answer "is there a one line way of doing this?"
if 'key' in my_dict: del my_dict['key']
...well, you asked ;-)
You should consider, though, that this way of deleting an object from a dict is not atomic—it is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of
try:
del my_dict['key']
except KeyError:
pass
which, of course, is definitely not a one-liner.
It took me some time to figure out what exactly my_dict.pop("key", None) is doing. So I'll add this as an answer to save others googling time:
pop(key[, default])
If key is in the dictionary, remove it and return its value, else
return default. If default is not given and key is not in the
dictionary, a KeyError is raised.
Documentation
del my_dict[key] is slightly faster than my_dict.pop(key) for removing a key from a dictionary when the key exists
>>> import timeit
>>> setup = "d = {i: i for i in range(100000)}"
>>> timeit.timeit("del d[3]", setup=setup, number=1)
1.79e-06
>>> timeit.timeit("d.pop(3)", setup=setup, number=1)
2.09e-06
>>> timeit.timeit("d2 = {key: val for key, val in d.items() if key != 3}", setup=setup, number=1)
0.00786
But when the key doesn't exist if key in my_dict: del my_dict[key] is slightly faster than my_dict.pop(key, None). Both are at least three times faster than del in a try/except statement:
>>> timeit.timeit("if 'missing key' in d: del d['missing key']", setup=setup)
0.0229
>>> timeit.timeit("d.pop('missing key', None)", setup=setup)
0.0426
>>> try_except = """
... try:
... del d['missing key']
... except KeyError:
... pass
... """
>>> timeit.timeit(try_except, setup=setup)
0.133
If you need to remove a lot of keys from a dictionary in one line of code, I think using map() is quite succinct and Pythonic readable:
myDict = {'a':1,'b':2,'c':3,'d':4}
map(myDict.pop, ['a','c']) # The list of keys to remove
>>> myDict
{'b': 2, 'd': 4}
And if you need to catch errors where you pop a value that isn't in the dictionary, use lambda inside map() like this:
map(lambda x: myDict.pop(x,None), ['a', 'c', 'e'])
[1, 3, None] # pop returns
>>> myDict
{'b': 2, 'd': 4}
or in python3, you must use a list comprehension instead:
[myDict.pop(x, None) for x in ['a', 'c', 'e']]
It works. And 'e' did not cause an error, even though myDict did not have an 'e' key.
You can use a dictionary comprehension to create a new dictionary with that key removed:
>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}
You can delete by conditions. No error if key doesn't exist.
You can use exception handling if you want to be very verbose:
try:
del dict[key]
except KeyError: pass
This is slower, however, than the pop() method, if the key doesn't exist.
my_dict.pop('key', None)
It won't matter for a few keys, but if you're doing this repeatedly, then the latter method is a better bet.
The fastest approach is this:
if 'key' in dict:
del myDict['key']
But this method is dangerous because if 'key' is removed in between the two lines, a KeyError will be raised.
We can delete a key from a Python dictionary by the some of the following approaches.
Using the del keyword; it's almost the same approach like you did though -
myDict = {'one': 100, 'two': 200, 'three': 300 }
print(myDict) # {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : del myDict['one']
print(myDict) # {'two': 200, 'three': 300}
Or
We can do like the following:
But one should keep in mind that, in this process actually it won't delete any key from the dictionary rather than making a specific key excluded from that dictionary. In addition, I observed that it returned a dictionary which was not ordered the same as myDict.
myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
{key:value for key, value in myDict.items() if key != 'one'}
If we run it in the shell, it'll execute something like {'five': 500, 'four': 400, 'three': 300, 'two': 200} - notice that it's not the same ordered as myDict. Again if we try to print myDict, then we can see all keys including which we excluded from the dictionary by this approach. However, we can make a new dictionary by assigning the following statement into a variable:
var = {key:value for key, value in myDict.items() if key != 'one'}
Now if we try to print it, then it'll follow the parent order:
print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}
Or
Using the pop() method.
myDict = {'one': 100, 'two': 200, 'three': 300}
print(myDict)
if myDict.get('one') : myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
The difference between del and pop is that, using pop() method, we can actually store the key's value if needed, like the following:
myDict = {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : var = myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
print(var) # 100
Fork this gist for future reference, if you find this useful.
I prefer the immutable version
foo = {
1:1,
2:2,
3:3
}
removeKeys = [1,2]
def woKeys(dct, keyIter):
return {
k:v
for k,v in dct.items() if k not in keyIter
}
>>> print(woKeys(foo, removeKeys))
{3: 3}
>>> print(foo)
{1: 1, 2: 2, 3: 3}
Another way is by using items() + dict comprehension.
items() coupled with dict comprehension can also help us achieve the task of key-value pair deletion, but it has the drawback of not being an in place dict technique. Actually a new dict if created except for the key we don’t wish to include.
test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21}
# Printing dictionary before removal
print ("dictionary before performing remove is : " + str(test_dict))
# Using items() + dict comprehension to remove a dict. pair
# removes vinod
new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'}
# Printing dictionary after removal
print ("dictionary after remove is : " + str(new_dict))
Output:
dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}

How can I remove a key from a Python dictionary?

I want to remove a key from a dictionary if it is present. I currently use this code:
if key in my_dict:
del my_dict[key]
Without the if statement, the code will raise KeyError if the key is not present. How can I handle this more simply?
See Delete an element from a dictionary for more general approaches to the problem of removing a key from a dict (including ones which produce a modified copy).
To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():
my_dict.pop('key', None)
This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.
To delete a key that is guaranteed to exist, you can also use
del my_dict['key']
This will raise a KeyError if the key is not in the dictionary.
Specifically to answer "is there a one line way of doing this?"
if 'key' in my_dict: del my_dict['key']
...well, you asked ;-)
You should consider, though, that this way of deleting an object from a dict is not atomic—it is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of
try:
del my_dict['key']
except KeyError:
pass
which, of course, is definitely not a one-liner.
It took me some time to figure out what exactly my_dict.pop("key", None) is doing. So I'll add this as an answer to save others googling time:
pop(key[, default])
If key is in the dictionary, remove it and return its value, else
return default. If default is not given and key is not in the
dictionary, a KeyError is raised.
Documentation
del my_dict[key] is slightly faster than my_dict.pop(key) for removing a key from a dictionary when the key exists
>>> import timeit
>>> setup = "d = {i: i for i in range(100000)}"
>>> timeit.timeit("del d[3]", setup=setup, number=1)
1.79e-06
>>> timeit.timeit("d.pop(3)", setup=setup, number=1)
2.09e-06
>>> timeit.timeit("d2 = {key: val for key, val in d.items() if key != 3}", setup=setup, number=1)
0.00786
But when the key doesn't exist if key in my_dict: del my_dict[key] is slightly faster than my_dict.pop(key, None). Both are at least three times faster than del in a try/except statement:
>>> timeit.timeit("if 'missing key' in d: del d['missing key']", setup=setup)
0.0229
>>> timeit.timeit("d.pop('missing key', None)", setup=setup)
0.0426
>>> try_except = """
... try:
... del d['missing key']
... except KeyError:
... pass
... """
>>> timeit.timeit(try_except, setup=setup)
0.133
If you need to remove a lot of keys from a dictionary in one line of code, I think using map() is quite succinct and Pythonic readable:
myDict = {'a':1,'b':2,'c':3,'d':4}
map(myDict.pop, ['a','c']) # The list of keys to remove
>>> myDict
{'b': 2, 'd': 4}
And if you need to catch errors where you pop a value that isn't in the dictionary, use lambda inside map() like this:
map(lambda x: myDict.pop(x,None), ['a', 'c', 'e'])
[1, 3, None] # pop returns
>>> myDict
{'b': 2, 'd': 4}
or in python3, you must use a list comprehension instead:
[myDict.pop(x, None) for x in ['a', 'c', 'e']]
It works. And 'e' did not cause an error, even though myDict did not have an 'e' key.
You can use a dictionary comprehension to create a new dictionary with that key removed:
>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}
You can delete by conditions. No error if key doesn't exist.
You can use exception handling if you want to be very verbose:
try:
del dict[key]
except KeyError: pass
This is slower, however, than the pop() method, if the key doesn't exist.
my_dict.pop('key', None)
It won't matter for a few keys, but if you're doing this repeatedly, then the latter method is a better bet.
The fastest approach is this:
if 'key' in dict:
del myDict['key']
But this method is dangerous because if 'key' is removed in between the two lines, a KeyError will be raised.
We can delete a key from a Python dictionary by the some of the following approaches.
Using the del keyword; it's almost the same approach like you did though -
myDict = {'one': 100, 'two': 200, 'three': 300 }
print(myDict) # {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : del myDict['one']
print(myDict) # {'two': 200, 'three': 300}
Or
We can do like the following:
But one should keep in mind that, in this process actually it won't delete any key from the dictionary rather than making a specific key excluded from that dictionary. In addition, I observed that it returned a dictionary which was not ordered the same as myDict.
myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
{key:value for key, value in myDict.items() if key != 'one'}
If we run it in the shell, it'll execute something like {'five': 500, 'four': 400, 'three': 300, 'two': 200} - notice that it's not the same ordered as myDict. Again if we try to print myDict, then we can see all keys including which we excluded from the dictionary by this approach. However, we can make a new dictionary by assigning the following statement into a variable:
var = {key:value for key, value in myDict.items() if key != 'one'}
Now if we try to print it, then it'll follow the parent order:
print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}
Or
Using the pop() method.
myDict = {'one': 100, 'two': 200, 'three': 300}
print(myDict)
if myDict.get('one') : myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
The difference between del and pop is that, using pop() method, we can actually store the key's value if needed, like the following:
myDict = {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : var = myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
print(var) # 100
Fork this gist for future reference, if you find this useful.
I prefer the immutable version
foo = {
1:1,
2:2,
3:3
}
removeKeys = [1,2]
def woKeys(dct, keyIter):
return {
k:v
for k,v in dct.items() if k not in keyIter
}
>>> print(woKeys(foo, removeKeys))
{3: 3}
>>> print(foo)
{1: 1, 2: 2, 3: 3}
Another way is by using items() + dict comprehension.
items() coupled with dict comprehension can also help us achieve the task of key-value pair deletion, but it has the drawback of not being an in place dict technique. Actually a new dict if created except for the key we don’t wish to include.
test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21}
# Printing dictionary before removal
print ("dictionary before performing remove is : " + str(test_dict))
# Using items() + dict comprehension to remove a dict. pair
# removes vinod
new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'}
# Printing dictionary after removal
print ("dictionary after remove is : " + str(new_dict))
Output:
dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}
Remove multiple keys
Marc Maxmeister's post discusses this but creates an unnecessary (imo) list while doing so. You can simply use a for-loop and throw away the popped values.
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
lst = ['a', 'c', 'e']
for k in lst: my_dict.pop(k, None)
print(my_dict) # {'b': 2, 'd': 4}
or if you want to use map, then exhaust the map using a deque with max length 0.
from collections import deque
from itertools import repeat
deque(map(my_dict.pop, ['a', 'c', 'e'], repeat(None)), 0)
print(my_dict) # {'b': 2, 'd': 4}
Split dict into two
One case where dict.pop() may be useful is if you want to create a new dictionary with the popped key-value pairs, effectively splitting a dictionary into two in one for-loop.
new_dict = {k: v for k in lst if (v:=my_dict.pop(k, 'NULL')) != 'NULL'}
print(my_dict) # {'b': 2, 'd': 4}
print(new_dict) # {'a': 1, 'c': 3}

Remove an item from a dictionary when its key is unknown

What is the best way to remove an item from a dictionary by value, i.e. when the item's key is unknown? Here's a simple approach:
for key, item in some_dict.items():
if item is item_to_remove:
del some_dict[key]
Are there better ways? Is there anything wrong with mutating (deleting items) from the dictionary while iterating it?
The dict.pop(key[, default]) method allows you to remove items when you know the key. It returns the value at the key if it removes the item otherwise it returns what is passed as default. See the docs.'
Example:
>>> dic = {'a':1, 'b':2}
>>> dic
{'a': 1, 'b': 2}
>>> dic.pop('c', 0)
0
>>> dic.pop('a', 0)
1
>>> dic
{'b': 2}
Be aware that you're currently testing for object identity (is only returns True if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==). If you are doing this on purpose, then you could rewrite your code as
some_dict = {key: value for key, value in some_dict.items()
if value is not value_to_remove}
But this may not do what you want:
>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}
So you probably want != instead of is not.
a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']
A simple comparison between del and pop():
import timeit
code = """
results = {'A': 1, 'B': 2, 'C': 3}
del results['A']
del results['B']
"""
print timeit.timeit(code, number=100000)
code = """
results = {'A': 1, 'B': 2, 'C': 3}
results.pop('A')
results.pop('B')
"""
print timeit.timeit(code, number=100000)
result:
0.0329667857143
0.0451040902256
So, del is faster than pop().
I'd build a list of keys that need removing, then remove them. It's simple, efficient and avoids any problem about simultaneously iterating over and mutating the dict.
keys_to_remove = [key for key, value in some_dict.iteritems()
if value == value_to_remove]
for key in keys_to_remove:
del some_dict[key]
items() returns a list, and it is that list you are iterating, so mutating the dict in the loop doesn't matter here. If you were using iteritems() instead, mutating the dict in the loop would be problematic, and likewise for viewitems() in Python 2.7.
I can't think of a better way to remove items from a dict by value.
c is the new dictionary, and a is your original dictionary, {'z','w'}
are the keys you want to remove from a
c = {key:a[key] for key in a.keys() - {'z', 'w'}}
Also check: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch01.html
y={'username':'admin','machine':['a','b','c']}
if 'c' in y['machine'] : del y['machine'][y['machine'].index('c')]
There is nothing wrong with deleting items from the dictionary while iterating, as you've proposed. Be careful about multiple threads using the same dictionary at the same time, which may result in a KeyError or other problems.
Of course, see the docs at http://docs.python.org/library/stdtypes.html#typesmapping
This is how I would do it.
for key in some_dict.keys():
if some_dict[key] == item_to_remove:
some_dict.pop(key)
break

How do I delete items from a dictionary while iterating over it?

Can I delete items from a dictionary in Python while iterating over it?
I want to remove elements that don't meet a certain condition from the dictionary, instead of creating an entirely new dictionary. Is the following a good solution, or are there better ways?
for k, v in mydict.items():
if k == val:
del mydict[k]
For Python 3+:
>>> mydict
{'four': 4, 'three': 3, 'one': 1}
>>> for k in list(mydict.keys()):
... if mydict[k] == 3:
... del mydict[k]
>>> mydict
{'four': 4, 'one': 1}
The other answers work fine with Python 2 but raise a RuntimeError for Python 3:
RuntimeError: dictionary changed size during iteration.
This happens because mydict.keys() returns an iterator not a list.
As pointed out in comments simply convert mydict.keys() to a list by list(mydict.keys()) and it should work.
For Python 2:
A simple test in the console shows you cannot modify a dictionary while iterating over it:
>>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> for k, v in mydict.iteritems():
... if k == 'two':
... del mydict[k]
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
As stated in delnan's answer, deleting entries causes problems when the iterator tries to move onto the next entry. Instead, use the keys() method to get a list of the keys and work with that:
>>> for k in mydict.keys():
... if k == 'two':
... del mydict[k]
>>> mydict
{'four': 4, 'three': 3, 'one': 1}
If you need to delete based on the items value, use the items() method instead:
>>> for k, v in mydict.items():
... if v == 3:
... del mydict[k]
>>> mydict
{'four': 4, 'one': 1}
You could also do it in two steps:
remove = [k for k in mydict if k == val]
for k in remove: del mydict[k]
My favorite approach is usually to just make a new dict:
# Python 2.7 and 3.x
mydict = { k:v for k,v in mydict.items() if k!=val }
# before Python 2.7
mydict = dict((k,v) for k,v in mydict.iteritems() if k!=val)
Iterate over a copy instead, such as the one returned by items():
for k, v in list(mydict.items()):
You can't modify a collection while iterating it. That way lies madness - most notably, if you were allowed to delete and deleted the current item, the iterator would have to move on (+1) and the next call to next would take you beyond that (+2), so you'd end up skipping one element (the one right behind the one you deleted). You have two options:
Copy all keys (or values, or both, depending on what you need), then iterate over those. You can use .keys() et al for this (in Python 3, pass the resulting iterator to list). Could be highly wasteful space-wise though.
Iterate over mydict as usual, saving the keys to delete in a seperate collection to_delete. When you're done iterating mydict, delete all items in to_delete from mydict. Saves some (depending on how many keys are deleted and how many stay) space over the first approach, but also requires a few more lines.
It's cleanest to use list(mydict):
>>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> for k in list(mydict):
... if k == 'three':
... del mydict[k]
...
>>> mydict
{'four': 4, 'two': 2, 'one': 1}
This corresponds to a parallel structure for lists:
>>> mylist = ['one', 'two', 'three', 'four']
>>> for k in list(mylist): # or mylist[:]
... if k == 'three':
... mylist.remove(k)
...
>>> mylist
['one', 'two', 'four']
Both work in python2 and python3.
With python3, iterate on dic.keys() will raise the dictionary size error. You can use this alternative way:
Tested with python3, it works fine and the Error "dictionary changed size during iteration" is not raised:
my_dic = { 1:10, 2:20, 3:30 }
# Is important here to cast because ".keys()" method returns a dict_keys object.
key_list = list( my_dic.keys() )
# Iterate on the list:
for k in key_list:
print(key_list)
print(my_dic)
del( my_dic[k] )
print( my_dic )
# {}
You can use a dictionary comprehension.
d = {k:d[k] for k in d if d[k] != val}
You could first build a list of keys to delete, and then iterate over that list deleting them.
dict = {'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4}
delete = []
for k,v in dict.items():
if v%2 == 1:
delete.append(k)
for i in delete:
del dict[i]
There is a way that may be suitable if the items you want to delete are always at the "beginning" of the dict iteration
while mydict:
key, value = next(iter(mydict.items()))
if should_delete(key, value):
del mydict[key]
else:
break
The "beginning" is only guaranteed to be consistent for certain Python versions/implementations. For example from What’s New In Python 3.7
the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.
This way avoids a copy of the dict that a lot of the other answers suggest, at least in Python 3.
I tried the above solutions in Python3 but this one seems to be the only one working for me when storing objects in a dict. Basically you make a copy of your dict() and iterate over that while deleting the entries in your original dictionary.
tmpDict = realDict.copy()
for key, value in tmpDict.items():
if value:
del(realDict[key])
One-liner:
my_dict = {k: v for k, v in my_dict.copy().items() if not k == value}
The my_dict.copy() object is used for the iteration only and will not be available outside the scope of the dictionary comprehension. This avoids editing the object over which you are currently iterating, as advised against by #user395760 in their answer.
You can split this over multiple lines for clarity:
my_dict = {
k: v
for k, v in my_dict.copy().items()
if not k == value
}

Iterating over dictionaries using 'for' loops

d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
How does Python recognize that it needs only to read the key from the dictionary? Is key a special keyword, or is it simply a variable?
key is just a variable name.
for key in d:
will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:
For Python 3.x:
for key, value in d.items():
For Python 2.x:
for key, value in d.iteritems():
To test for yourself, change the word key to poop.
In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better.
This is also available in 2.7 as viewitems().
The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).
It's not that key is a special word, but that dictionaries implement the iterator protocol. You could do this in your class, e.g. see this question for how to build class iterators.
In the case of dictionaries, it's implemented at the C level. The details are available in PEP 234. In particular, the section titled "Dictionary Iterators":
Dictionaries implement a tp_iter slot that returns an efficient
iterator that iterates over the keys of the dictionary. [...] This
means that we can write
for k in dict: ...
which is equivalent to, but much faster than
for k in dict.keys(): ...
as long as the restriction on modifications to the dictionary
(either by the loop or by another thread) are not violated.
Add methods to dictionaries that return different kinds of
iterators explicitly:
for key in dict.iterkeys(): ...
for value in dict.itervalues(): ...
for key, value in dict.iteritems(): ...
This means that for x in dict is shorthand for for x in
dict.iterkeys().
In Python 3, dict.iterkeys(), dict.itervalues() and dict.iteritems() are no longer supported. Use dict.keys(), dict.values() and dict.items() instead.
Iterating over a dict iterates through its keys in no particular order, as you can see here:
(This is no longer the case in Python 3.6, but note that it's not guaranteed behaviour yet.)
>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> list(d)
['y', 'x', 'z']
>>> d.keys()
['y', 'x', 'z']
For your example, it is a better idea to use dict.items():
>>> d.items()
[('y', 2), ('x', 1), ('z', 3)]
This gives you a list of tuples. When you loop over them like this, each tuple is unpacked into k and v automatically:
for k,v in d.items():
print(k, 'corresponds to', v)
Using k and v as variable names when looping over a dict is quite common if the body of the loop is only a few lines. For more complicated loops it may be a good idea to use more descriptive names:
for letter, number in d.items():
print(letter, 'corresponds to', number)
It's a good idea to get into the habit of using format strings:
for letter, number in d.items():
print('{0} corresponds to {1}'.format(letter, number))
key is simply a variable.
For Python2.X:
>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> for my_var in d:
>>> print my_var, 'corresponds to', d[my_var]
x corresponds to 1
y corresponds to 2
z corresponds to 3
... or better,
d = {'x': 1, 'y': 2, 'z': 3}
for the_key, the_value in d.iteritems():
print the_key, 'corresponds to', the_value
For Python3.X:
d = {'x': 1, 'y': 2, 'z': 3}
for the_key, the_value in d.items():
print(the_key, 'corresponds to', the_value)
When you iterate through dictionaries using the for .. in ..-syntax, it always iterates over the keys (the values are accessible using dictionary[key]).
To iterate over key-value pairs, use the following:
for k,v in dict.iteritems() in Python 2
for k,v in dict.items() in Python 3
This is a very common looping idiom. in is an operator. For when to use for key in dict and when it must be for key in dict.keys() see David Goodger's Idiomatic Python article (archived copy).
I have a use case where I have to iterate through the dict to get the key, value pair, also the index indicating where I am. This is how I do it:
d = {'x': 1, 'y': 2, 'z': 3}
for i, (key, value) in enumerate(d.items()):
print(i, key, value)
Note that the parentheses around the key, value are important, without them, you'd get an ValueError "not enough values to unpack".
Iterating over dictionaries using 'for' loops
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
...
How does Python recognize that it needs only to read the key from the
dictionary? Is key a special word in Python? Or is it simply a
variable?
It's not just for loops. The important word here is "iterating".
A dictionary is a mapping of keys to values:
d = {'x': 1, 'y': 2, 'z': 3}
Any time we iterate over it, we iterate over the keys. The variable name key is only intended to be descriptive - and it is quite apt for the purpose.
This happens in a list comprehension:
>>> [k for k in d]
['x', 'y', 'z']
It happens when we pass the dictionary to list (or any other collection type object):
>>> list(d)
['x', 'y', 'z']
The way Python iterates is, in a context where it needs to, it calls the __iter__ method of the object (in this case the dictionary) which returns an iterator (in this case, a keyiterator object):
>>> d.__iter__()
<dict_keyiterator object at 0x7fb1747bee08>
We shouldn't use these special methods ourselves, instead, use the respective builtin function to call it, iter:
>>> key_iterator = iter(d)
>>> key_iterator
<dict_keyiterator object at 0x7fb172fa9188>
Iterators have a __next__ method - but we call it with the builtin function, next:
>>> next(key_iterator)
'x'
>>> next(key_iterator)
'y'
>>> next(key_iterator)
'z'
>>> next(key_iterator)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
When an iterator is exhausted, it raises StopIteration. This is how Python knows to exit a for loop, or a list comprehension, or a generator expression, or any other iterative context. Once an iterator raises StopIteration it will always raise it - if you want to iterate again, you need a new one.
>>> list(key_iterator)
[]
>>> new_key_iterator = iter(d)
>>> list(new_key_iterator)
['x', 'y', 'z']
Returning to dicts
We've seen dicts iterating in many contexts. What we've seen is that any time we iterate over a dict, we get the keys. Back to the original example:
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
If we change the variable name, we still get the keys. Let's try it:
>>> for each_key in d:
... print(each_key, '=>', d[each_key])
...
x => 1
y => 2
z => 3
If we want to iterate over the values, we need to use the .values method of dicts, or for both together, .items:
>>> list(d.values())
[1, 2, 3]
>>> list(d.items())
[('x', 1), ('y', 2), ('z', 3)]
In the example given, it would be more efficient to iterate over the items like this:
for a_key, corresponding_value in d.items():
print(a_key, corresponding_value)
But for academic purposes, the question's example is just fine.
For Iterating through dictionaries, The below code can be used.
dictionary= {1:"a", 2:"b", 3:"c"}
#To iterate over the keys
for key in dictionary.keys():
print(key)
#To Iterate over the values
for value in dictionary.values():
print(value)
#To Iterate both the keys and values
for key, value in dictionary.items():
print(key,'\t', value)
You can check the implementation of CPython's dicttype on GitHub. This is the signature of method that implements the dict iterator:
_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
PyObject **pvalue, Py_hash_t *phash)
CPython dictobject.c
To iterate over keys, it is slower but better to use my_dict.keys(). If you tried to do something like this:
for key in my_dict:
my_dict[key+"-1"] = my_dict[key]-1
it would create a runtime error because you are changing the keys while the program is running. If you are absolutely set on reducing time, use the for key in my_dict way, but you have been warned.
If you are looking for a clear and visual example:
cat = {'name': 'Snowy', 'color': 'White' ,'age': 14}
for key , value in cat.items():
print(key, ': ', value)
Result:
name: Snowy
color: White
age: 14
This will print the output in sorted order by values in ascending order.
d = {'x': 3, 'y': 1, 'z': 2}
def by_value(item):
return item[1]
for key, value in sorted(d.items(), key=by_value):
print(key, '->', value)
Output:
y -> 1
z -> 2
x -> 3
Let's get straight to the point. If the word key is just a variable, as you have mentioned then the main thing to note is that when you run a 'FOR LOOP' over a dictionary it runs through only the 'keys' and ignores the 'values'.
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print (key, 'corresponds to', d[key])
rather try this:
d = {'x': 1, 'y': 2, 'z': 3}
for i in d:
print (i, 'corresponds to', d[i])
but if you use a function like:
d = {'x': 1, 'y': 2, 'z': 3}
print(d.keys())
in the above case 'keys' is just not a variable, its a function.
A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key. A key's value can be a number, a string, a list, or even another dictionary. In this case, threat each "key-value pair" as a separate row in the table: d is your table with two columns. the key is the first column, key[value] is your second column. Your for loop is a standard way to iterate over a table.

Categories

Resources