简体   繁体   中英

Order a dict in python when keys are list

I need to order the following dict in asc order depends on the progreso value. How can I do it?

{
    10: [{"titulo": "Apropiación Digital"}, {"progreso": "50"}, {"estado": "En curso"}],
    13: [
        {"titulo": "Así se ve mi negocio"},
        {"progreso": "0"},
        {"estado": "En espera"},
    ],
    8: [{"titulo": "Bioseguridad"}, {"progreso": "50"}, {"estado": "En curso"}],
    15: [
        {"titulo": "Desarrollo de oportunidades de negocio"},
        {"progreso": "0"},
        {"estado": "En espera"},
    ],
    9: [{"titulo": "Formalización"}, {"progreso": "0"}, {"estado": "En espera"}],
    11: [{"titulo": "Hagamos cuentas"}, {"progreso": "50"}, {"estado": "En curso"}],
    7: [
        {"titulo": "Mujer emprendedora"},
        {"progreso": "100"},
        {"estado": "Finalizado"},
        {"puntaje": 100},
        {"fecha": datetime.datetime(2021, 3, 31, 15, 19, 20)},
        {"puntos": 170},
    ],
    12: [
        {"titulo": "Precio y competencia"},
        {"progreso": "0"},
        {"estado": "En espera"},
    ],
    14: [{"titulo": "Servicio al cliente"}, {"progreso": "0"}, {"estado": "En espera"}],
    16: [{"titulo": "Test"}, {"progreso": "0"}, {"estado": "En espera"}],
}

We know the location of the progreso value in the dictionary:

{10: [ .. , {'progresso':' x '}, ..], 13: [ .. ,x, .. ], ..}

so in this dictionary, you first have the name (dict for example), then the first integer, then the second element ( progress )

while True:
    tempDict = dict               # The dictionary will be equal to the temporary dictionary at the end of this loop if there are no more changes made to it.
    for i in dict[0:-2]:          # From first to second last element, to prevent it from looking beyond the last element
        if dict[i]['progreso'] < dict[i+1]['progreso']:
             dict[i],dict[i+1] = dict[i+1],dict[i] #swap places 'i' and 'i+1'
    if tempDict == dict: # Now that changes may have been made, we can test for it, and possibly exit the loop.
        break

something along those lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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