我想对可能有int或tuple作为键的字典进行双重排序。
d = {33:1, 44:1, (0,5):1 12:2, (1,2):2}
我希望它首先按其值排序,然后按其键排序(如果可能,不是如果一个是元组,第二个是int)。
任何人都可以帮我这个吗?
提前致谢
答案 0 :(得分:4)
或者只是
sorted(d.items(), key=lambda v: v[::-1])
修改强> 由于OP需要将结果作为字典
OrderedDict(sorted(d.items(), key=lambda v: v[::-1]))
答案 1 :(得分:1)
>>> d = {33:1, 44:1, (0,5):1, 12:2, (1,2):2}
>>> {k:v for k,v in sorted(d.items(), key=lambda v: v[::-1])}
{(1, 2): 2, 33: 1, 44: 1, (0, 5): 1, 12: 2}
>>> from collections import OrderedDict
>>> OrderedDict({k:v for k,v in sorted(d.items(), key=lambda v: v[::-1])})
OrderedDict([((1, 2), 2), (33, 1), (44, 1), ((0, 5), 1), (12, 2)])
>>> sorted(d.items(), key=lambda v: v[::-1])
[(33, 1), (44, 1), ((0, 5), 1), (12, 2), ((1, 2), 2)]
答案 2 :(得分:0)
这个怎么样?
>>> d = {33:1, 44:1, (0,5):1, 12:2, (1,2):2}
>>> helper_dict = {}
>>> for k,v in d.items():
helper_dict.setdefault(v,[]).append(k)
>>> sorted_items = [(k,i) for k in sorted(helper_dict.keys()) for i in sorted(helper_dict[k]) ]
>>> sorted_items
[(1, 33), (1, 44), (1, (0, 5)), (2, 12), (2, (1, 2))]
答案 3 :(得分:0)
首先,您应该注意,您可能不对字典进行排序。您可能会获得一个列表,其中键/值已排序,但从不是字典本身。您可以在pydocs中找到
最好将字典视为一组无序的键:值 对
然后,您可能想要获得一个按键排序列表:
# the .keys() returns a list with all the keys, and sorted() sorts them
#sorted_keys = sorted(d.keys()) this does not work since int's and tuples aren't of the same tipe
你可以试试这个:
d_tuples = []
d_int = []
sorted_keys = []
for key in d.keys():
# type() checks the variable type
if type(key) == int:
d_int.append(key)
elif type(key) == tuple:
d_tuples.append(key)
sorted_keys = d_tuples + sorted(d_int)
或排序的值列表:
sorted_values = sorted(d.values())