按值排序字典和字符串化的有效方法

2024-03-29 14:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本带字符串键和int值的字典

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

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

我需要按值排序并返回一个json字符串。你知道吗

以下工作:

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

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

但我觉得效率不高


Tags: 字符串injsonsharefor字典queryresp
1条回答
网友
1楼 · 发布于 2024-03-29 14:30:32

Python 3解决方案:

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))

输出:

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

编辑:

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))

输出:

{'table': 5, 'cheese': 4, 'pizza': 3, 'share': 1, 'eating': 1}
{"table": 5, "cheese": 4, "pizza": 3, "share": 1, "eating": 1}
网友
2楼 · 发布于 2024-03-29 14:30:32
json.dumps(sorted(yourdict.items(), key=operator.itemgetter(1),reverse=True))

你可以找到更多的细节 Here

相关问题 更多 >