python - Unexpected behaviour when creating dictionary -
this question has reply here:
why order in python dictionaries , sets arbitrary? 5 answersword = 'pythonist' #splitting word alphabets newword = [] char in word: newword.append(char) print newword ########################## #creating dict d = {} length = len(word) x in range(0,length): d["{0}".format(x)] = newword[x] print d
if notice dictionary key:value not in same order letters in string 'pythonist'. causing behaviour? im thinking, it's way dictionary created because im letting values dict taken list created?
your code can simplified quite bit:
from collections import ordereddict word = 'pythonist' d = ordereddict() x, c in enumerate(word): d["{0}".format(x)] = c print d
this code produces output:
ordereddict([('0', 'p'), ('1', 'y'), ('2', 't'), ('3', 'h'), ('4', 'o'), ('5', 'n'), ('6', 'i'), ('7', 's'), ('8', 't')])
as can see, courtesy of ordereddict
, output in order.
there no need split word
newword
. in python, strings iterables.
in computer programming, need constructions appears often:
for x in range(0,length): d["{0}".format(x)] = newword[x]
for reason, python created enumerate
gives both x
, , newword[x]
@ same time.
the documentation ordereddict
here. reasons of speed, conventional python dictionaries unordered. when not satisfactory, utilize class ordereddict
.
python dictionary
No comments:
Post a Comment