I have data in the dictionary and want to get it in another dictionary but inserted/sorted in the following way:
the items sorted in a descending way for keys the first letter:
'z':1, ...., 'a':1
but inside of groups of items, which have the same first letter, to have opposite sort direction:
'aaa':1, 'abb':1, 'acc':1, ....
Here I have my example of code for this task(sorted by key), it works but I am looking for something more elegant:
my_dict = {
'abc': 'aaaa',
'bus': 'bbba',
'apple': 'abbb',
'banana': 'bbaa',
'angel': 'aabb',
'baseball': 'baaa',
}
starting_letters = reversed(sorted({k[0] for k in my_dict.keys()}))
result = {}
for i in starting_letters:
intermediate = {}
for k in my_dict.keys():
if k.startswith(i):
intermediate[k] = my_dict[k]
result.update(dict(sorted(intermediate.items())))
print(result)
this is the output:
{'banana': 'bbaa', 'baseball': 'baaa', 'bus': 'bbba', 'abc': 'aaaa', 'angel': 'aabb', 'apple': 'abbb'}
as you can see it's sorted descending: (items with key starting on b goes before items with key starting on a) but groups of items are sorted ascending:
'banana': 'bbaa', 'baseball': 'baaa', 'bus': 'bbba'
'abc': 'aaaa', 'angel': 'aabb', 'apple': 'abbb'