首页 > 解决方案 > Python 整理出一个复杂的字典

问题描述

我列了一个清单

data = [{"type":"house", "cost":500, "extra":False, "order":1}, 
{"type":"condo", "cost":40, "extra":False, "order":4}, 
{"type":"house", "cost":120, "extra":True, "order":2}, 
{"type":"house", "cost":800, "extra":True, "order":3}]

order并希望按键对数据进行排序

你会怎么解决?

标签: pythondictionary

解决方案


您不是在对字典进行排序,而是在对字典列表进行排序。

尝试这个:

data = [{"type":"house", "cost":500, "extra":False, "order":1}, 
{"type":"condo", "cost":40, "extra":False, "order":4}, 
{"type":"house", "cost":120, "extra":True, "order":2}, 
{"type":"house", "cost":800, "extra":True, "order":3}]

length = len (data)
for index1 in range (length) :
    for index2 in range (length) :
        if data [index2]['order'] > data [index1]['order'] :
            data [index2], data [index1] = data [index1], data [index2]
print (data)

推荐阅读