Traverse the dict in Python
We usually use the following 2 ways to traverse a dict:
1: for d in dic 2: for d in dic.keys()
Which one is better? Let's have a look at one simple demo.
#!/usr/bin/python dic = {'a': 1, 'b': 2, 'c': 1} print(dic) for d in dic: if dic[d] == 1: del(dic[d]) print(dic)
What we get is an RuntimeError: "dictionary changed size during iteration". Now let's try the 2nd method as follows.
#!/usr/bin/python dic = {'a': 1, 'b': 2, 'c': 1} print(dic) # dic.keys() is recommended. #for d in dic: # NOT OK #RuntimeError: dictionary changed size during iteration for d in dic.keys(): # OK if dic[d] == 1: del(dic[d]) print(dic)
And we got the expected result.
Let's take a simple analysis: in the 1st demo code, the target we traverse is the dict itself, and we delete
the first element whose value is 1 in the iteration, so the dictionary(target we traverse)'s size is changed
during the iteration, then we get the RuntimeError. While in the 2nd demo code, the target we traverse is not
the dict itself but the dic.keys() --which is ['a', 'b', 'c'], so during the iteration the size of the target is not
changed.
So, maybe we could draw the conclusion that sometimes(when we modify the dict during the traversing)
the 2nd method to traverse a dict is safer than the 1st one.
Update:
For Python3.+ the 1st demo code does NOT work, and we still got the error message "RuntimeError: dictionary changed size during iteration".
> In Python3.+ we need to use `for k in list(mydict.keys())`:
as Python3.+ makes the `keys()` method an iterator, and also disallows
> deleting dict items during iteration. By adding a `list()` call we turn the `keys()` iterator into a list. So when we are in the body of the for loop we
> are no longer iterating over the dictionary itself.
References:
python编程细节──遍历dict的两种方法比较: http://blogread.cn/it/article/2438?f=sr
How to delete items from a dictionary while iterating over it? https://stackoverflow.com/questions/5384914/how-to-delete-items-from-a-dictionary-while-iterating-over-it