简体   繁体   English

Python中JSON中元素的翻转顺序

[英]Flip order of elements in JSON in Python

I can't seem to find a solution for this but suppose I have JSON data: 我似乎找不到解决方案,但假设我有JSON数据:

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

How do I reverse the order of color and score so it's: 我如何颠倒颜色和分数的顺序,所以是:

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

While the order of the items does not matter, if you really wanted to have a certain order you could use an OrderedDict . 尽管项目的顺序无关紧要,但是如果您确实想拥有一定的顺序,则可以使用OrderedDict

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

How I write in comment you should sort your dicts and convert them into OrderedDicts 我如何写评论,您应该对字典进行排序并将其转换为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')])]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM