0

我有一个数据结构如下:

[
{
original_price: {
value: ""
},
promos: [ ],
local_id: "122863",
url: "link",
title: "abc",
current_price: {
value: 19.5
},
image: "link",
selections: {
color: "BLACK",
length: "",
size: "7"
},
store: "abc"
},
{
original_price: {
value: ""
},
promos: [ ],
local_id: "122863",
url: "link",
title: "abc",
current_price: {
value: 19.5
},
image: "link",
selections: {
color: "BLACK",
length: "",
size: "9"
},
store: "abc"
},
{
original_price: {
value: ""
},
promos: [ ],
local_id: "122863",
url: "link",
title: "abc",
current_price: {
value: 19.5
},
image: "link",
selections: {
color: "BLACK",
length: "",
size: "6"
},
store: "abc"
}
]

我尝试使用代码按“大小”键对其进行排序:

def order_size(self, raw_sizes): 
     for i in range(len(raw_sizes)):
         print i
         for j in range(i+1, len(raw_sizes)):
             #print raw_sizes
             if raw_sizes[j]['selections']['size'] < raw_sizes[i]['selections']['size']:
                 raw_sizes[j], raw_sizes[i] = raw_sizes[i], raw_sizes[j]


     #print raw_sizes
     return raw_sizes

但我不能。请帮我。我期望结果:

[
{
original_price: {
value: ""
},
promos: [ ],
local_id: "122863",
url: "link",
title: "abc",
current_price: {
value: 19.5
},
image: "link",
selections: {
color: "BLACK",
length: "",
size: "6"
},
store: "abc"
},
{
original_price: {
value: ""
},
promos: [ ],
local_id: "122863",
url: "link",
title: "abc",
current_price: {
value: 19.5
},
image: "link",
selections: {
color: "BLACK",
length: "",
size: "7"
},
store: "abc"
},
{
original_price: {
value: ""
},
promos: [ ],
local_id: "122863",
url: "link",
title: "abc",
current_price: {
value: 19.5
},
image: "link",
selections: {
color: "BLACK",
length: "",
size: "9"
},
store: "abc"
}
]

这个 dict 列表按 dict 中的 dict 键排序

4

1 回答 1

4

那是冒泡排序吗?真的吗?

无论如何,没有必要编写自己的排序函数:

raw_sizes.sort(key=lambda d: d['selections']['size'])
于 2013-03-28T09:13:43.387 回答