-3

I want to sort this nested dictionary twice. First, I want to sort by time, and then by key. This is a nested nested dictionary. The time should be filtered first and then by keys ("FileNameXXX") of the inner dictionary.

data = {1: {"05:00:00": {"FileName123": "LineString1"}},
        2: {"16:00:00": {"FileName456": "LineString2"}},
        3: {"07:00:00": {"FileName789": "LineString3"}},
        4: {"07:00:00": {"FileName555": "LineString4"}}}

Expected Result:

1: {"05:00:00": {"FileName123": "LineString1"}}
3: {"07:00:00": {"FileName789": "LineString3"}}
4: {"07:00:00": {"FileName555": "LineString4"}}
2: {"16:00:00": {"FileName456": "LineString2"}}
HelloWorld123
  • 79
  • 2
  • 9

1 Answers1

1

You can achieve that by building some notion of value for each entry in data. For example, I defined the "value" of a data entry in the following function but notice that it heavily relies on having exactly one key inside the second nested dict which must also be strictly a time formatted as string.

def get_comparable(key):
    raw_time = list(data[key].keys())[0]
    time = datetime.strptime(raw_time, "%H:%M:%S").time()
    return time.hour * 3600 + time.minute * 60 + time.second + key * 0.001

The you can just use:

for k in sorted(data, key=get_comparable):
    print(k, data[k])

output:

1 {'05:00:00': {'FileName123': 'LineString1'}}
3 {'07:00:00': {'FileName789': 'LineString3'}}
4 {'07:00:00': {'FileName555': 'LineString4'}}
2 {'16:00:00': {'FileName456': 'LineString2'}}

Using

sorted(data, key=lambda x: list(data[x].keys())[0])

will produce the same output but be careful and notice that it will not take into account the values of first level keys (the numbers) and that will sort the times lexicographically.