3

I want output dictionary Keys/Vals same as below:

{'pid': '10076', 'nick': 'Jonas', 'time': '2714', 'score': '554'}

But after loop I got output like this:

{'nick': 'Jonas', 'score': '554', 'pid': '10076', 'time': '2714'}

What I can 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

1 Answers1

1

Dictionaries are unordered in (and in very much all of ). So you can never assume that the order will be the same as the one you add the elements in.

You can however use OrderedDict from the collections package which is a dictionary (it supports all the functions of a dictionary) and maintains the order in which you add elements:

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

This then prints:

>>> print stats
OrderedDict([('pid', '10076'), ('nick', 'Jonas'), ('time', '2714'), ('score', '554')])
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555