Good day. There is a dictionary of the following content:

{"среда": "физика", "четверг": "русский", "понедельник": "схемотехника", "пятница": "выходной", "вторник": "география"} 

And there is a list of such content:

 ["понедельник", "вторник", "среда", "четверг", "пятница"] 

Can you please tell me how to sort the dictionary by list? Well, or even bring it into normal form (so that the days of the week go in order)?

    1 answer 1

    The python dictionary does not preserve the order of the elements.

    You can use a special ordered dictionary type - OrderedDict.

    For example, here’s how you can get OrderedDict correctly ordered from your dictionary and list:

     from collections import OrderedDict source_dict = { "среда": "физика", "четверг": "русский", "понедельник": "схемотехника", "пятница": "выходной", "вторник": "география" } week = ["понедельник", "вторник", "среда", "четверг", "пятница"] result = OrderedDict() for day in week: result[day] = source_dict[day] print(result) # Вы получите: OrderedDict([('понедельник', 'схемотехника'), ('вторник', 'география'), ('среда', 'физика'), ('четверг', 'русский'), ('пятница', 'выходной')]) 

    Well, or you can write a little more concise, if you are familiar with the generator expressions:

     from collections import OrderedDict source_dict = { "среда": "физика", "четверг": "русский", "понедельник": "схемотехника", "пятница": "выходной", "вторник": "география" } week = ["понедельник", "вторник", "среда", "четверг", "пятница"] result = OrderedDict((day, source_dict[day]) for day in week) print(result) # Результат тот же самый 

    UPD: A little corrected in accordance with the comments from Timofey Bondarev - for which he thanks.

    • one
      Something I made out my decision for a long time. In yours, you can simplify adding an item to the dictionary: instead of using update you can use assignment on the index result[day] = source_dict[day] - Timofei Bondarev
    • Thank you very much, you really helped - Plato
    • @TimofeyBondarev, yes good point. So really it turns out more clearly. - Xander
    • one
      And in the list generator it is not necessary to create a list, you can use the generator expression: OrderedDict((day, source_dict[day]) for day in week) - Timofei Bondarev
    • one
      or the essence: OrderedDict(zip(week, itemgetter(*week)(source_dict))) or OrderedDict(zip(week, map(source_dict.get, week))) . Both are less readable (in normal code, I would prefer the version with a generator suggested by @TimofeyBondarev) - jfs