How to sort a dictionary based on a list in python

后端 未结 2 1220
后悔当初
后悔当初 2021-02-05 06:16

I have a dictionary

a = {\'ground\': obj1, \'floor 1\': obj2, \'basement\': obj3}

I have a list.

a_list = [\'floor 1\', \'grou         


        
2条回答
  •  无人及你
    2021-02-05 06:44

    You could just retrieve the values in order of the keys provided by the list and make a new list out of the key-value pairs.

    Example:

    d = a      # dictionary containing key-value pairs that are to be ordered
    l = a_list # list of keys that represent the order for the dictionary
    # retrieve the values in order and build a list of ordered key-value pairs
    ordered_dict_items = [(k,d[k]) for k in l]
    

提交回复
热议问题