在Python中的字典内按字典键排序列表

时间:2013-03-28 09:09:05

标签: python list sorting

我有一个数据结构如下:

[
{
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"
}
]

我尝试使用'size'键对其进行排序,代码为:

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键排序

1 个答案:

答案 0 :(得分:4)

这是一个冒泡吗?真的?

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

raw_sizes.sort(key=lambda d: d['selections']['size'])