¿Cómo ordenar la salida mientras recorre el diccionario por variable miembro? [duplicar]

how to sort dictiony by member variable

class Item():
    def __init__(self, _name, _index, _price):
        self.name = _name
        self.index = _index
        self.price = _price

I want to show item information ordered by index or price.

DicItems = {}
DicItems["Candy"] = Item("Candy", 1, 100)
DicItems["IceCream"] = Item("IceCream", 2, 500)
DicItems["Snack"] = Item("Snack", 3, 300)

print items list order by index ->result

Candy     1 100
IceCream  2 500
Snack     3 300

print items list order by price ->result

Candy       1 100
Snack       3 300
IceCream    2 500

preguntado el 27 de noviembre de 13 a las 07:11

3 Respuestas

Código de preparación:

class Item():
    def __init__(self, _name, _index, _price):
        self.name = _name
        self.index = _index
        self.price = _price
    def items(self):
        return self.name, self.index, self.price

d = {}
d["Candy"] = Item("Candy", 1, 100)
d["IceCream"] = Item("IceCream", 2, 500)
d["Snack"] = Item("Snack", 3, 300)

Sorting Code:

print [item.items() for item in sorted(d.values(), key = lambda x:x.index)]
print [item.items() for item in sorted(d.values(), key = lambda x:x.price)]

Salida

[('Candy', 1, 100), ('IceCream', 2, 500), ('Snack', 3, 300)]
[('Candy', 1, 100), ('Snack', 3, 300), ('IceCream', 2, 500)]

Or we can generalize it with atractivo como este

from operator import attrgetter
def sorter(d, key):
    return [item.items() for item in sorted(d.values(), key = attrgetter(key))]

print sorter(d, "index")
print sorter(d, "name")
print sorter(d, "price")

Salida

[('Candy', 1, 100), ('IceCream', 2, 500), ('Snack', 3, 300)]
[('Candy', 1, 100), ('IceCream', 2, 500), ('Snack', 3, 300)]
[('Candy', 1, 100), ('Snack', 3, 300), ('IceCream', 2, 500)]

respondido 27 nov., 13:08

¿Por qué no solo [item[1].items() for item in sorted(d.items(), key=lambda x: x[1].index)]? Doing tons of lookups on the dict parece innecesario. - gareth latty

@Lattyware Changed it. We don't even need items(), He utilizado values() :) - los cuatro ojos

Indeed, that looks good. +1. - gareth latty

@Lattyware Thanks :) I generalized with attrgetter :) - los cuatro ojos

lambda x: getter(x)) kind of defies the point there - getter hará lo mismo. - gareth latty

Dictionaries in python do not have any order.

For what you want, it can be achieved by doing following:

from operator import  attrgetter
name_getter = attrgetter('name')
index_getter = attrgetter('index')
price_getter = attrgetter('price')

sorted_by_index = sorted(DicItems, key=index_getter)
sorted_by_name = sorted(DicItems, key=name_getter)
sorted_by_price = sorted(DicItems, key=price_getter)

respondido 27 nov., 13:08

Esto no proporciona una respuesta a la pregunta. Para criticar o solicitar una aclaración de un autor, deje un comentario debajo de su publicación. - Raptor

@ShivanRaptor: Yes, that was my lack of patience. Fixed now. - 0xc0de

more difficult, but more universally

from operator import attrgetter

class DictItems(dict):

     def sortByPrice():
         return sorted(self.values(), key=attrgetter('price'))

     def sortByIndex():
         return sorted(self.values(), key=attrgetter('index'))

d = DictItems()
d["Candy"] = Item("Candy", 1, 100)
d["IceCream"] = Item("IceCream", 2, 500)
d["Snack"] = Item("Snack", 3, 300)

d.sortByPrice()
d.sortByIndex()

respondido 27 nov., 13:08

maybe valuesSortedByPrice and valuesSortedByIndex would be better names, making it clearer that you are returning a new list of sorted values - jbat100

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.