jeudi 30 octobre 2014

python iterating over dictionaries sorted by values


Vote count:

0




Piece of code below. Can anyone explain why iterating over dictionary, last lines, that has been sorted by values still outputs dictionary not sorted by values? Same applies when I try saving the dictionary.



#!/usr/bin/python

x = {1: 2999, 3: 4, 4: 3, 2: 1, 0: 0 }
srtkeys = sorted(x, key=x.get)
ds={}
print "\ncreating dict sorted by values"
for w in srtkeys:`enter code here`
print w,x[w]
ds[w] = x[w]

print "\nprinting dict sorted by values"
print ds

print "\niterating over dict sorted by values"
for k,v in ds.iteritems():
print str(k)+":"+str(v)


Output:



creating dict sorted by values
0 0
2 1
4 3
3 4
1 2999

printing dict sorted by values
{0: 0, 1: 2999, 2: 1, 3: 4, 4: 3}

iterating over dict sorted by values
0:0
1:2999
2:1
3:4
4:3


asked 58 secs ago







python iterating over dictionaries sorted by values

Aucun commentaire:

Enregistrer un commentaire