【问题标题】:Python sort JSON by array value [closed]Python按数组值对JSON进行排序[关闭]
【发布时间】:2019-03-14 09:13:17
【问题描述】:

我有一个这样的 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) 

但这看起来不适用,我有点卡住了。如何做到这一点?

【问题讨论】:

  • @DirtyBit 哦,好评论,我会更新一个问题!
  • @RnD 干杯,以后会这样做!
  • 这不是排序,而是替换dict中第二个元素的值。
  • 您通过编辑您的问题不断地更改所需的输出。如果您希望人们提供帮助,请坚持使用。
  • @MilesDavisi 只编辑过一次,我想知道为什么它经历了用户多次编辑(并且只接受了 1 次更改,带有漂亮的 JSON)

标签: python json


【解决方案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}]

【讨论】:

  • 这正是我想要的。非常感谢,感谢您使用 lambda !我想我必须深入挖掘:)
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    试试这个

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 2012-11-30
      • 2019-12-18
      相关资源
      最近更新 更多