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

  • 相关阅读:
    免费webservice接口
    sql server按符号截取字符串
    javaweb项目部署到tomcat服务器
    sql server导出数据结构
    Mabits简单应用 2017.8.3
    部署项目到tomcat步骤参考如下 2017.7.10
    没事多看文档 2017.7.8
    ssh商城源码 2017.6.30
    axios的详细用法以及后端接口代理
    用Vue来实现音乐播放器(八):自动轮播图啊
  • 原文地址:https://www.cnblogs.com/lxw0109/p/traverse_dict.html
Copyright © 2011-2022 走看看