Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.4 wrong keys position in dictionary after loop [duplicate]

Tags:

python

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 Answers

Dictionaries are unordered in python-2.x (and in very much all of python-3.x). 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')])
like image 105
Willem Van Onsem Avatar answered Jun 27 '26 12:06

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!