Reputation: 65
I have to sort dictionary values in ascending order. Then I have to exclude zero element from dictionary. I have found lots of example of sorting dictionary by keys or values not values itself. Any help on this?
Input:
1467606570.0,192.168.123.241,0.0
1467606817.0,192.168.123.241,247.0
1467607136.0,192.168.123.241,319.0
1467607244.0,192.168.123.241,108.0
1467607642.0,192.168.123.241,398.0
1467608334.0,192.168.123.241,692.0
1467606628.0,192.168.123.240,0.0
1467606876.0,192.168.123.240,248.0
1467607385.0,192.168.123.240,509.0
1467606679.0,192.168.123.246,0.0
1467607084.0,192.168.123.246,405.0
1467607713.0,192.168.123.246,629.0
1467608102.0,192.168.123.246,389.0
1467607524.0,192.168.123.242,0.0
1467608257.0,192.168.123.242,733.0
1467608607.0,192.168.123.242,350.0
1467608669.0,192.168.123.245,0.0
1467608813.0,192.168.123.245,144.0
Code:
mydict = {}
#sorted_dict = {}
reader = csv.reader(open("/tmp/log/qpm.csv", "rb"))
for i, rows in enumerate(reader):
if i == 0: continue
k = rows[1]
v = rows[2]
if not k in mydict:
mydict[k] = [v]
else:
mydict[k].append(v)
#for key, value in mydict.iteritems():
for key, value in sorted (mydict.iteritems(), key=operator.itemgetter(1),reverse=True):
print key, value
Output :
192.168.123.241 ['247.0', '319.0', '108.0', '398.0', '692.0']
192.168.123.242 ['0.0', '733.0', '350.0']
192.168.123.246 ['0.0', '405.0', '629.0', '389.0']
192.168.123.240 ['0.0', '248.0', '509.0']
192.168.123.245 ['0.0', '144.0']
Required Output:
192.168.123.241 ['108.0', '319.0', '398.0', '692.0']
192.168.123.242 ['0.0', '350.0', '733.0']
192.168.123.246 ['0.0', '389.0', '405.0', '629.0']
192.168.123.240 ['0.0', '248.0', '509.0']
192.168.123.245 ['0.0', '144.0']
How sort values in ascending order?
Upvotes: 0
Views: 418
Reputation: 836
Based on the sample output I suspect you want to sort the values for each key? If so you could do this by changing your print statement to be:
print key, sorted(value)
Note that the entries in the values
list are strings and so will sort in lexicological order which I suspect is not what your want. To sort as floats you can specify a custom comparator:
print key, sorted(value, key=lambda x: float(x))
Alternatively you could store the values as floats when you initially read the data:
if not k in mydict:
mydict[k] = [float(v)]
else:
mydict[k].append(float(v))
Upvotes: 1