[英]Sorting a dict by keys consisting of numbers and letters
I have a dict that contains data about different quarters (of years):我有一个包含不同季度(年份)的数据的字典:
"data": {
"Q3/2016": 86,
"Q1/2016": 85,
"Q4/2016": 69,
"Q2/2016": 69,
"Q2/2017": 82,
"Q1/2017": 66,
},
How can I sort this so it looks like this我怎样才能对它进行排序,使它看起来像这样
"data": {
"Q1/2016": 85,
"Q2/2016": 69,
"Q3/2016": 86,
"Q4/2016": 69,
"Q1/2017": 66,
"Q2/2017": 82,
},
Dictionaries cannot be ordered in-place since they have no order, but since Python 3.7 they remember insertion order so we can build an "ordered" dictionary by sorting key-value pairs from your unordered dictionary.字典不能就地排序,因为它们没有顺序,但是从 Python 3.7 开始,它们会记住插入顺序,因此我们可以通过对无序字典中的键值对进行排序来构建“有序”字典。
So the actual important part is the key
we pass as an argument to sorted
.所以真正重要的部分是我们作为参数传递给
sorted
的key
。 In the following code, the key is a lambda function that takes each key, split it at /
and reverses the resulting tuple, so that keys are sorted first by year, then by quarter:在下面的代码中,键是 lambda function ,它获取每个键,将其拆分为
/
并反转生成的元组,以便键首先按年份排序,然后按季度排序:
d = {"data": {
"Q3/2016": 86,
"Q1/2016": 85,
"Q4/2016": 69,
"Q2/2016": 69,
"Q2/2017": 82,
"Q1/2017": 66,
}
}
d['data'] = {k: v for k, v in sorted(d['data'].items(), key=lambda x: x[0].split('/')[::-1])}
print(d)
output: output:
{'data': {
'Q1/2016': 85,
'Q2/2016': 69,
'Q3/2016': 86,
'Q4/2016': 69,
'Q1/2017': 66,
'Q2/2017': 82}
}
You should copy this dict into an ordered dict like你应该把这个字典复制到一个有序的字典中,比如
In [22]: from collections import OrderedDict
In [23]: data = {
...: "Q3/2016": 86,
...: "Q1/2016": 85,
...: "Q4/2016": 69,
...: "Q2/2016": 69,
...: "Q2/2017": 82,
...: "Q1/2017": 66,
...: }
In [40]: def sort_key(key_val):
...: key, val = key_val
...: key = key.split("/")
...: return int(key[1]), key[0]
...:
# add a custom sort key
In [24]: data = OrderedDict(sorted(data.items(), key=sort_key))
In [25]: data
Out[25]:
OrderedDict([('Q1/2016', 85),
('Q2/2016', 69),
('Q3/2016', 86),
('Q4/2016', 69),
('Q1/2017', 66),
('Q2/2017', 82)])
It seems to maintain the order while json serialisation too which is nice似乎在 json 序列化的同时也保持顺序,这很好
In [27]: print(json.dumps(data, indent=4))
{
"Q1/2016": 85,
"Q2/2016": 69,
"Q3/2016": 86,
"Q4/2016": 69,
"Q1/2017": 66,
"Q2/2017": 82
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.