简体   繁体   English

Python 排序嵌套字典

[英]Python sort nested dictionary

I want to sort this nested dictionary twice.我想对这个嵌套字典进行两次排序。 First, I want to sort by time, and then by key.首先,我想按时间排序,然后按key。 This is a nested nested dictionary.这是一个嵌套的嵌套字典。 The time should be filtered first and then by keys ("FileNameXXX") of the inner dictionary.时间应先过滤,然后通过内部字典的键(“FileNameXXX”)过滤。

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"}}

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.例如,我在下面的 function 中定义了数据条目的“值”,但请注意,它严重依赖于在第二个嵌套 dict 中只有一个键,该键也必须严格地格式化为字符串的时间。

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: 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.将产生相同的 output 但要小心并注意它不会考虑第一级键(数字)的值,并且会按字典顺序对时间进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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