zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    二手房交易平台需求分析心得——字节移动小组
    结对编程之个人项目代码分析
    五月最新版 重装win10软件
    学习必备的——超级有用的网站!!!
    SQL中sa被禁用
    19 erp沙盘校赛
    temp
    Bootstrap 学习日志(二)
    Bootstrap 学习日志(一)
    关于Android上进行模拟登陆时的验证码问题
  • 原文地址:https://www.cnblogs.com/lxw0109/p/traverse_dict.html
Copyright © 2011-2022 走看看