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
enumeratefunction is probably the easiest way to create yourdict:However, I’m not sure what that gives you that you can’t do with the string. The following seem equivalent to me: