Python 2.4 wrong position in dictionary after loop
I want the Keys / Vals output dictionary to be the same as below:
{'pid': '10076', 'nick': 'Jonas', 'time': '2714', 'score': '554'}
But after the loop I got the output like this:
{'nick': 'Jonas', 'score': '554', 'pid': '10076', 'time': '2714'}
What can I do to avoid this?
datalines = ['pid\tnick\ttime\tscore', '10076\tJonas\t2714\t554']
stats = {}
keys = datalines[0].split('\t')
vals = datalines[1].split('\t')
for idx in range(0,len(keys)):
stats[keys[idx]] = vals[idx]
print stats
+3
user3801788
source
to share
1 answer
Dictionaries are unordered in python-2.x (and throughout the text python-3.x). Therefore, you can never assume that the order will be the same as the one you add to the elements.
However, you can use OrderedDict
from a package collections
, which is a dictionary (it supports all the functions of a dictionary) and maintains the order in which you add items:
from collections import OrderedDict
datalines = ['pid\tnick\ttime\tscore', '10076\tJonas\t2714\t554']
stats = OrderedDict()
keys = datalines[0].split('\t')
vals = datalines[1].split('\t')
for idx in range(0,len(keys)):
stats[keys[idx]] = vals[idx]
print stats
Then it prints:
>>> print stats
OrderedDict([('pid', '10076'), ('nick', 'Jonas'), ('time', '2714'), ('score', '554')])
+1
source to share