I have the following snippet of code which I ran in python2.7.12 and python3.5.2
f = open(file_name,'r')
file_data= f.read()
f.close()
char_list = list(set(file_data))
c = {char:i for i,char in enumerate(char_list)}
x = {i:char for i,char in enumerate(char_list)}
When ran in python2.7.12 I get the expected result :
{'a': 0, ' ': 1, 'e': 2, 'i': 3, 'h': 4, '\n': 5, 'o': 6, 'r': 7, 'u': 8, 'w': 9, 'y': 10, '?': 11}
{0: 'a', 1: ' ', 2: 'e', 3: 'i', 4: 'h', 5: '\n', 6: 'o', 7: 'r', 8: 'u', 9: 'w', 10: 'y', 11: '?'}
In python3.5.2, something strange happens. I sometimes get results such as :
{'h': 1, 'e': 4, 'r': 2, 'i': 3, '?': 0, '\n': 5, ' ': 6, 'u': 7, 'a': 8, 'y': 9, 'o': 10, 'w': 11}
{0: '?', 1: 'h', 2: 'r', 3: 'i', 4: 'e', 5: '\n', 6: ' ', 7: 'u', 8: 'a', 9: 'y', 10: 'o', 11: 'w'}
In addition, in python3.5.2, but not python2.7.12, each time the program is ran char_list
is in a different order. It is in the same order every time for python2.7.12.
In both version of python enumerate
returns an object that is iterable.
Why would this strange behavior be happening?
P.S. this also happens when I make a copy of char_list
and pass the copy into the second enumerate instead of char_list