简体   繁体   English

Python:如何按相似键对字典列表进行排序

[英]Python: How to sort a list of dictionaries by similar keys

I have this data and would like to sort them like this我有这些数据,想像这样对它们进行排序

input:输入:

[{'POINT': 0.1}, {'POINT': 0.2}, {'THRESHOLD': 0.1}, {'THRESHOLD': 0.4}, {'INDEX': 0.3}, {'INDEX': 0.9}]

I want the output to be like this我希望 output 是这样的

[
{'POINT': 0.1, 'THRESHOLD': 0.1, 'INDEX': 0.3},
{'POINT': 0.2, 'THRESHOLD': 0.4, 'INDEX': 0.9}

I have tried iterating over the list and keeping tracks of the keys but it doesn't seem smart to me.我曾尝试遍历列表并跟踪键,但对我来说似乎并不聪明。

Assuming I understood the problem setup correctly, you can do this:假设我正确理解了问题设置,您可以这样做:

pd.DataFrame({k: list(v.dropna()) for k, v in pd.DataFrame(x).items()}).to_dict('records')

This way values are used in the order they appear in, if you want them sorted, use sorted instead of list :这种方式值按照它们出现的顺序使用,如果你想让它们排序,使用sorted而不是list

pd.DataFrame({k: sorted(v.dropna()) for k, v in pd.DataFrame(x).items()}).to_dict('records')

In case it does not have to be the list of dictionaries, you can display it in a pandas dataframe.如果它不必是字典列表,您可以在 pandas dataframe 中显示它。 That would also make it easier for you to do any task on your data.这也将使您更容易对数据执行任何任务。

import pandas as pd


l = [{'POINT': 0.1}, {'POINT': 0.2}, {'THRESHOLD': 0.1}, {'THRESHOLD': 0.4}, {'INDEX': 0.3}, {'INDEX': 0.9}]

result_d, keys = {}, []
for d in l:
    key = list(d.keys())[0]
    if key not in keys:
        keys.append(key)
        result_d[key] = []
        for d2 in l:
            key2 = list(d2.keys())[0]
            if key2 == keys[-1]:
                result_d[key].append(d2[key2])

print(result_d)

Output: Output:

{'POINT': [0.1, 0.2], 'THRESHOLD': [0.1, 0.4], 'INDEX': [0.3, 0.9]}

Construct DataFrame from dict:从dict构造DataFrame:

pd.DataFrame(result_d)

Output: Output:

   POINT  THRESHOLD  INDEX
0    0.1        0.1    0.3
1    0.2        0.4    0.9

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

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