Python按数组值对JSON进行排序

时间:2019-03-14 09:13:17

标签: python json

我有这样的JSON

[{'percentage': {'negative': [3132394, 0.73],
                 'neutral': [388133213, 90.18],
                 'positive': [39129393, 9.09]},
  'source_id': 2,
  'total': 430395000},
 {'percentage': {'negative': [3132394, 0.73],
                 'neutral': [388133213, 90.18],
                 'positive': [39129393, 9.09]},
  'source_id': 2,
  'total': 430395000}]

如何按percentage及其百分比值排序(每个字典(neutralpositivenegative)中列表的第二个对象

我尝试过这个:

sorted(dict[key], key=lambda function) 

但是这似乎不适用,我有点卡住了。该怎么做?

3 个答案:

答案 0 :(得分:1)

我不确定您的问题,因为它已进行了大量修改。我认为这就是您要搜索的...

>>>p
[{'percentage': {'negative': [3132394, 0.73],
   'neutral': [388133213, 90.18],
   'positive': [39129393, 9.09]},
  'source_id': 2,
  'total': 430395000},
 {'percentage': {'negative': [3132394, 0.73],
   'neutral': [388133213, 90.18],
   'positive': [39129393, 9.09]},
  'source_id': 2,
  'total': 430395000}]
>>>for i in p:
    i["percentage"]=sorted(i["percentage"].items(),key=lambda x:x[1],reverse=True)
>>>p
[{'percentage': [('neutral', [388133213, 90.18]),
   ('positive', [39129393, 9.09]),
   ('negative', [3132394, 0.73])],
  'source_id': 2,
  'total': 430395000},
 {'percentage': [('neutral', [388133213, 90.18]),
   ('positive', [39129393, 9.09]),
   ('negative', [3132394, 0.73])],
  'source_id': 2,
  'total': 430395000}]

答案 1 :(得分:0)

您可以对列表进行排序。因此,您可以使用字典本身包含的一个或多个值作为关键字来对包含字典的列表进行排序,但是无法对字典进行排序。字典不能那样工作。

https://docs.python.org/3/library/stdtypes.html#dict

答案 2 :(得分:0)

尝试一下

data = [{'percentage': {'negative': [3132394, 0.73],
                        'neutral': [388133213, 90.18],
                        'positive': [39129393, 9.09]},
         'source_id': 2,
         'total': 430395000},
        {'percentage': {'negative': [3132394, 0.73],
                        'neutral': [388133213, 90.18],
                        'positive': [39129393, 9.09]},
         'source_id': 2,
         'total': 430395000}]


def get_positive_pct(entry):
    # sort by the seconds element in the positive list - you can change it once your post is stable..
    return entry['percentage']['positive'][1]


sorted_data = sorted(data, key=get_positive_pct)