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

转载于:https://www.cnblogs.com/lxw0109/p/traverse_dict.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值