我似乎找不到解决方案,但假设我有 JSON 数据:
data = [{"color":"blue","score":"3"},{"color":"red","score":"2"},....]
我如何颠倒颜色和得分的顺序,所以它是:
data = [{"score":"3","color":"blue"},{"score":"2","color":"red"},....]
虽然项目的顺序无关紧要,但如果您真的想要某个顺序,您可以使用OrderedDict。
>>> from collections import OrderedDict
>>> data = [OrderedDict([("score", "3"),("color", "blue")])]
>>> json.dumps(data)
'[{"score": "3", "color": "blue"}]'
我如何在评论中写你应该对你的字典进行排序并将它们转换为 OrderedDicts
from collections import OrderedDict
a = {'score':3, 'color':'red'}
b = {'score':1, 'color':'yellow'}
lst = []
for d in [a,b]:
temp = OrderedDict()
for k in sorted(d, reverse=True):
temp.setdefault(k, d[k])
lst.append(temp)
OUTPUT: [OrderedDict([('score', 3), ('color', 'red')]), OrderedDict([('score', 1), ('color', 'yellow')])]