0

I have a dictionary with string keys and int values

for word in coocc[query]:
    resp[word]=coocc[query][word]

{"share": 1, "pizza": 3, "eating": 1,...}

I need to sort by value and return a json string.

The following works:

sortedList=sorted(resp.items(), key=operator.itemgetter(1), reverse=True)
sortedDict=collections.OrderedDict(sortedList)
return json.dumps(sortedDict)

'{"cheese": 4, "pizza": 3, "table": 3,..}

but it doesn't seems very efficient to me

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
eddie
  • 415
  • 4
  • 13

2 Answers2

0
json.dumps(sorted(yourdict.items(), key=operator.itemgetter(1),reverse=True))

you can find more details Here

eddie
  • 415
  • 4
  • 13
Fahim Ahmed
  • 141
  • 11
0

Python 3 solution:

d = {"share": 1, "pizza": 3, "eating": 1,"table": 5, "cheese": 4 }
sorted = dict(sorted(d.items(), key=lambda x: x[1]))
print(sorted)
print (json.dumps(sorted))

output:

{'share': 1, 'eating': 1, 'pizza': 3, 'cheese': 4, 'table': 5}
{"share": 1, "eating": 1, "pizza": 3, "cheese": 4, "table": 5}

EDIT:

import json
d = {"share": 1, "pizza": 3, "eating": 1,"table": 5, "cheese": 4 }
sorted = dict(sorted(d.items(), key=lambda x: x[1], reverse = True))
print(sorted)
print (json.dumps(sorted))

output:

{'table': 5, 'cheese': 4, 'pizza': 3, 'share': 1, 'eating': 1}
{"table": 5, "cheese": 4, "pizza": 3, "share": 1, "eating": 1}
ncica
  • 7,015
  • 1
  • 15
  • 37