在Python中翻转JSON中元素的顺序

时间:2012-11-08 19:20:10

标签: python json

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

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

如何反转颜色和得分的顺序,以便:

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

2 个答案:

答案 0 :(得分:0)

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

>>> from collections import OrderedDict
>>> data = [OrderedDict([("score", "3"),("color", "blue")])]
>>> json.dumps(data)
'[{"score": "3", "color": "blue"}]'

答案 1 :(得分:0)

我如何写评论你应该对你的dicts进行排序并将它们转换为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')])]