0

我似乎找不到解决方案,但假设我有 JSON 数据:

data = [{"color":"blue","score":"3"},{"color":"red","score":"2"},....]

我如何颠倒颜色和得分的顺序,所以它是:

data = [{"score":"3","color":"blue"},{"score":"2","color":"red"},....]
4

2 回答 2

0

虽然项目的顺序无关紧要,但如果您真的想要某个顺序,您可以使用OrderedDict

>>> from collections import OrderedDict
>>> data = [OrderedDict([("score", "3"),("color", "blue")])]
>>> json.dumps(data)
'[{"score": "3", "color": "blue"}]'
于 2012-11-08T19:22:19.663 回答
0

我如何在评论中写你应该对你的字典进行排序并将它们转换为 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')])]
于 2012-11-08T19:59:47.583 回答