Python two ways to traverse dictionaries (dict) comparison

Source: Internet
Author: User
Python has won a lot of programmers ' pro-gaze with its beautiful syntax and convenient built-in data structures.
There is a very useful data structure, which is the dictionary (dict), which is very simple to use. When it comes to traversing a dict structure, I think most people will think of the for-key in Dictobj method, and it is true that this method is applicable in most cases. But not completely safe, see the following example:
Copy CodeThe code is as follows:


#这里初始化一个dict
>>> d = {' A ': 1, ' B ': 0, ' C ': 1, ' d ': 0}
#本意是遍历dict, if you find that the value of the element is 0, delete it.
>>> for K in D:
... if d[k] = = 0:
... del (d[k])
...
Traceback (most recent):
File " ", line 1, in
Runtimeerror:dictionary changed size during iteration
#结果抛出异常了, two elements of 0, also delete only one.
>>> D
{' A ': 1, ' C ': 1, ' d ': 0}

>>> d = {' A ': 1, ' B ': 0, ' C ': 1, ' d ': 0}
#d. Keys () is an array of subscripts
>>> D.keys ()
[' A ', ' C ', ' B ', ' d ']
#这样遍历, there is no problem, because in fact this is the D.keys () this list constant traversal.
>>> for K in D.keys ():
... if d[k] = = 0:
... del (d[k])
...
>>> D
{' A ': 1, ' C ': 1}
#结果也是对的
>>>


In fact, this example is I simplified, I am in a multi-threaded program to find this problem, so, my advice is: when traversing dict, to develop the use for K in D.keys () habit.
However, if it is multi-threaded, so it is absolutely safe? Not necessarily: When all two threads have finished D.keys (), if two threads are to delete the same key, the first delete will be successful, after the deletion of that will certainly be reported Keyerror, this seems to be only by other means to ensure.


Another article: Dict performance comparison of two kinds of traversal modes

About the performance issues with parentheses and without parentheses in tangled dict traversal
Copy the Code code as follows:


for (d,x) in Dict.items ():
Print "Key:" +d+ ", Value:" +str (x)

For d,x in Dict.items ():
Print "Key:" +d+ ", Value:" +str (x)

Performance test results with parentheses and without parentheses:

Copy the Code code as follows:


Test results
Number of test strips: 15
Parenthesized start time: 2012-06-14 12:13:37.375000
Closing time with parentheses: 2012-06-14 12:13:37.375000
Time interval: 0:00:00
Start time without parentheses: 2012-06-14 12:13:37.375000
End time without brackets: 2012-06-14 12:13:37.375000
Time interval: 0:00:00

Number of test strips: 50
Parenthesized start time: 2012-06-14 12:13:57.921000
Closing time with parentheses: 2012-06-14 12:13:57.921000
Time interval: 0:00:00
Start time without parentheses: 2012-06-14 12:13:57.921000
End time without brackets: 2012-06-14 12:13:57.937000
Time interval: 0:00:00.016000
Number of test strips: 100
Parenthesized start time: 2012-06-14 11:53:57.453000
Closing time with parentheses: 2012-06-14 11:53:57.468000
Time interval: 0:00:00.015000
Start time without parentheses: 2012-06-14 11:53:57.468000
End time without brackets: 2012-06-14 11:53:57.531000
Time interval: 0:00:00.063000

Number of test strips: 150
Parenthesized start time: 2012-06-14 12:00:54.812000
Closing time with parentheses: 2012-06-14 12:00:54.828000
Time interval: 0:00:00.016000
Start time without parentheses: 2012-06-14 12:00:54.828000
End time without brackets: 2012-06-14 12:00:54.921000
Time interval: 0:00:00.093000

Number of test strips: 200
Parenthesized start time: 2012-06-14 11:59:54.609000
Closing time with parentheses: 2012-06-14 11:59:54.687000
Time interval: 0:00:00.078000
Start time without parentheses: 2012-06-14 11:59:54.687000
End time without brackets: 2012-06-14 11:59:54.734000
Time interval: 0:00:00.047000

Number of test strips: 500
Parenthesized start time: 2012-06-14 11:54:39.906000
Closing time with parentheses: 2012-06-14 11:54:40.078000
Time interval: 0:00:00.172000
Start time without parentheses: 2012-06-14 11:54:40.078000
End time without brackets: 2012-06-14 11:54:40.125000
Time interval: 0:00:00.047000

Number of test strips: 1000
Parenthesized start time: 2012-06-14 11:54:49.171000
Closing time with parentheses: 2012-06-14 11:54:49.437000
Time interval: 0:00:00.266000
Start time without parentheses: 2012-06-14 11:54:49.437000
End time without brackets: 2012-06-14 11:54:49.609000
Time interval: 0:00:00.172000

Number of test strips: 2000
Parenthesized start time: 2012-06-14 11:54:58.921000
Closing time with parentheses: 2012-06-14 11:54:59.328000
Time interval: 0:00:00.407000
Start time without parentheses: 2012-06-14 11:54:59.328000
End time without brackets: 2012-06-14 11:54:59.687000
Time interval: 0:00:00.359000

Number of test strips: 5000
Parenthesized start time: 2012-06-14 11:55:05.781000
Closing time with parentheses: 2012-06-14 11:55:06.734000
Time interval: 0:00:00.953000
Start time without parentheses: 2012-06-14 11:55:06.734000
End time without brackets: 2012-06-14 11:55:07.609000
Time interval: 0:00:00.875000

Number of test strips: 10000
Parenthesized start time: 2012-06-14 11:55:15.656000
Closing time with parentheses: 2012-06-14 11:55:17.390000
Time interval: 0:00:01.734000
Start time without parentheses: 2012-06-14 11:55:17.390000
End time without brackets: 2012-06-14 11:55:19.109000
Time interval: 0:00:01.719000

Number of test strips: 20000
Parenthesized start time: 2012-06-14 12:19:14.921000
Closing time with parentheses: 2012-06-14 12:19:18.593000
Time interval: 0:00:03.672000
Start time without parentheses: 2012-06-14 12:19:18.593000
End time without brackets: 2012-06-14 12:19:22.218000
Time interval: 0:00:03.625000


As we can see, the dict of the number of bars at 2001 is a bit higher with parentheses, but less execution time with no parentheses after more than 200 of the data.

Here is the test code:

Copy the Code code as follows:


Test code
#-*-Coding:utf-8-*-
Import Datetime,codecs

Dict = {}

For I in Xrange (0,20000):
Dict.setdefault ("name" +str (i))
dict["Name" +str (i)]= "name"

S=codecs.open (R ' C:\\dict.txt ', ' a ', ' utf-8 ')

def write (des):
S.write (Des.decode ("Utf-8"))

Write ("Number of test strips:")
Write (str (dict) + "\ r \ n")
Write ("Start with parentheses:")
A=datetime.datetime.now ()
S.write (str (a) + "\ r \ n")

for (d,x) in Dict.items ():
Print "Key:" +d+ ", Value:" +str (x)
Write ("With parentheses End time:")
B=datetime.datetime.now ()
Write (str (b) + "\ r \ n")
Write ("time interval:")
Write (str (b-a) + "\ r \ n")

Write ("Start time without parentheses:")
C=datetime.datetime.now ()
Write (str (c) + "\ r \ n")
For d,x in Dict.items ():
Print "Key:" +d+ ", Value:" +str (x)
Write ("End time without parentheses:")
D=datetime.datetime.now ()
Write (str (d) + "\ r \ n")
Write ("time interval:")
Write (str (d-c) + "\ r \ n")
Write ("\ r \ n")
S.close ()

There is no good way to solve the problem of Chinese garbled ....?

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.