0

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'

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
apet
  • 958
  • 14
  • 16
  • Are you asking about reversed alphabetical sorting? – mapf May 04 '20 at 15:34
  • 1
    What is your expected output here? – RoadRunner May 04 '20 at 15:34
  • Does this answer your question? [Python data structure sort list alphabetically](https://stackoverflow.com/questions/14032521/python-data-structure-sort-list-alphabetically) – mapf May 04 '20 at 15:35
  • A Python `dict` is an unordered data structure by definition. There is no way to "sort" a dict. – Tomalak May 04 '20 at 15:42
  • I've edited the question, please check last part where I try to explain it – apet May 04 '20 at 15:59
  • @Tomalak Incorrect - dicts preserve insertion order since Python 3.7. – wim May 04 '20 at 16:02
  • I have data in 'my_dict' inserted/sorted one way and want to get another dictionary(named 'result' in my question) with the same data inserted/sorted in the way mentioned in the question, How to get it? – apet May 04 '20 at 16:19
  • Does this answer your question? [How do I sort a dictionary by key?](https://stackoverflow.com/questions/9001509/how-do-i-sort-a-dictionary-by-key) – Karl Knechtel Apr 26 '23 at 17:11

1 Answers1

0

Karl Knechtel's suggestion has very good answers but I didn't find there exactly what I was looking for, so I have my own answer:

dict(
    sorted(
        sorted(my_dict.items()), 
        key=lambda x: x[0][0], 
        reverse=True
    )
)
apet
  • 958
  • 14
  • 16