I have a dictionary of lists such as:
test_dict = { 'a' : [[1, 6, 8], [2, 5, 9], [54, 1, 34]],
'b' : [[1, 3, 8], [2, 1, 9], [54, 2, 34]],
'c' : [[1, 1, 8], [2, 9, 9], [54, 7, 34]]
}
and I want to sort (ascending) each value list by the second element in every sublist. The desired output dictionary would be:
output_dict = { 'a' : [[54, 1, 34], [2, 5, 9], [1, 6, 8]],
'b' : [[2, 1, 9], [54, 2, 34], [1, 3, 8]],
'c' : [[1, 1, 8], [54, 7, 34], [2, 9, 9]]
}
I am trying:
sorted_dict = dict(sorted(test_dict.items(), key=lambda e: e[1][1]))
sorted_dict.items()
bit this does not seem to do anything.
You are looking to sort lists of lists in your dictionary values, not the order of dictionary keys . For this, you can use a dictionary comprehension:
res = {k: sorted(v, key=lambda x: x[1]) for k, v in test_dict.items()}
{'a': [[54, 1, 34], [2, 5, 9], [1, 6, 8]],
'b': [[2, 1, 9], [54, 2, 34], [1, 3, 8]],
'c': [[1, 1, 8], [54, 7, 34], [2, 9, 9]]}
For the functional equivalent, you can use key=operator.itemgetter(1)
. In Python 3.6+, your dictionary order should be maintained. Prior to 3.6 dictionaries are unordered and you should not expect any particular ordering of keys.
To order by key, you can use collections.OrderedDict
:
from collections import OrderedDict
res_ordered = OrderedDict(sorted(res.items(), key=lambda x: x[0]))
OrderedDict([('a', [[54, 1, 34], [2, 5, 9], [1, 6, 8]]),
('b', [[2, 1, 9], [54, 2, 34], [1, 3, 8]]),
('c', [[1, 1, 8], [54, 7, 34], [2, 9, 9]])])
You can do like below, it will update the existing dictionary
test_dict = { 'a' : [[1, 6, 8], [2, 5, 9], [54, 1, 34]],
'b' : [[1, 3, 8], [2, 1, 9], [54, 2, 34]],
'c' : [[1, 1, 8], [2, 9, 9], [54, 7, 34]]
}
for k, v in test_dict.items():
test_dict[k] = sorted(v, key=lambda e: e[1])
print(test_dict)
to create a new dictionary
test_dict = { 'a' : [[1, 6, 8], [2, 5, 9], [54, 1, 34]],
'b' : [[1, 3, 8], [2, 1, 9], [54, 2, 34]],
'c' : [[1, 1, 8], [2, 9, 9], [54, 7, 34]]
}
new_dict = {k:sorted(v, key=lambda e: e[1]) for k, v in test_dict.items()}
print(new_dict)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.