简体   繁体   中英

Is it more efficient to create a dictionary in python using zip or a list comprehension?

Lets say I want to set up a basic text encoding using a dictionary in python.

Two ways of doing this come to mind immediately - using zip, and using list comprehension.

characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ .,!;"
dict_a = dict((x, characters[x]) for x in xrange(0, 31))
dict_b = dict(zip(xrange(0, 31), characters))

Which of these is more efficient? (The real encoding is longer than 31, this is a toy example). Is the difference significant?

Alternatively, am I approaching this wrong and should be using something other than a dictionary? (I need to be able to go in both directions of encoding).

The enumerate function is probably the easiest way to create your dict :

dict_c = dict(enumerate(characters))

However, I'm not sure what that gives you that you can't do with the string. The following seem equivalent to me:

>>> dict_c[3]
'D'
>>> characters[3]
'D'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM