0

How can I sort a multilayer dictionary by rearrange the second layer dictionary's keys? I think an example would be a better way to present it.

The original multilayer dictionary:
{'John': {'Low >3 days': 3,'Low >1 day': 2,'High <1 day': 2,'High >3 days': 3,'Low <1 day': 1,'High >1 day': 1},'Mary': {'High >1 day': 5,'High >3 days': 1,'Low <1 day': 0, 'Low >1 day': 2, 'Low >3 days': 9, 'High <1 day': 5}}

I am trying to arrange the second layer dictionary with change the first layer dictionary and move the second layer key-value pair together at the same time. The order of the second layer dictionary key is High <1 day, Low <1 day, High >1 day, Low >1 day, High >3 days, Low >3 days. The expected output would be as follow:
{'John': {'High <1 day': 2,'Low <1 day': 1,'High >1 day': 1,'Low >1 day': 2,'High >3 days': 3,'Low >3 days': 3},'Mary': {'High <1 day': 5,'Low <1 day': 0,'High >1 day': 5,'Low >1 day': 2,'High >3 days': 1,'Low >3 days': 9}}

2 Answers2

0

To achieve this you would need an OrderedDict from the collections module. See this post for references.

Community
  • 1
  • 1
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
0

I think you have a fundamental misunderstanding of what a dictionary is. There is no point in sorting a dictionary's keys because the dictionary is unordered. It doesn't matter where/how the keys are in the dictionary. I think you have two options.


If you are dead-set on making your keys be in a particular order, you can use an ordered dict. This will remember the order in which you inserted your keys into your dictionary. If you already have your current dict, you can convert it to an ordered dict using the following code.

from collections import OrderedDict
exDict = #... put your dict here
keyOrder = ['High <1 day', 'Low <1 day', 'High >1 day', 'Low >1 day', 'High >3 days', 'Low >3 days']
ordDict = OrderedDict()
for k in exDict.keys():
    ordDict[k] = OrderedDict()
    for kO in keyOrder:
        ordDict[k][kO] = exDict[k][kO]

If you're trying to print out or access information in a specific order, then you should define a variable for the order of keys you want to access. Much like I did in defining keyorder above, you can create a variable and loop over that to access the dict keys in a specific order.


Another reference post.

Community
  • 1
  • 1
zephyr
  • 2,182
  • 3
  • 29
  • 51