I have a dictionary that basically matches a number to a character, e.g. foo = {'z':1, 'A':1, 'a':1, 'b':3}
. The dictionary is currently completely randomized both numerically and alphabetically, however I do know how to sort is numerically, but I currently just want sort the characters alphabetically regardless of capitalization. So far I have tried using sortednames=sorted(foo.keys(), key=lambda x:x.lower())
but that returns a list of the sorted characters and now the matching numbers are gone. Does anyone know how to solve this?
Asked
Active
Viewed 159 times
0

qwerties
- 31
- 4
-
2Can you post what you've attempted so far? – kingkupps Feb 20 '21 at 01:00
-
Ok, so technically I take in the dictionary completely unsorted by number and alphabetically. So far I have just sorted it numberically using: sorted_tuples = sorted(foo.items(), key = operator.itemgetter(1)) sorted_foo = {k: v for k, v in sorted_tuples} Where foo is my original completely unsorted dictionary. Now I am thinking maybe if I can first sort it alphabetically then I can use the previous code and then sort it numerically after I have sorted it alphabetically. – qwerties Feb 20 '21 at 01:06
-
Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Show me how to solve this coding problem” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. – Prune Feb 20 '21 at 01:08
-
1Do these answer your question? [How do I do a case-insensitive string comparison?](https://stackoverflow.com/questions/319426/how-do-i-do-a-case-insensitive-string-comparison), [Sort python list by function](https://stackoverflow.com/q/7135836/4518341), [How do I sort a dictionary by value?](https://stackoverflow.com/q/613183/4518341), and [Sorting a dictionary by value then key](https://stackoverflow.com/q/9919342/4518341) – wjandrea Feb 20 '21 at 01:16
-
Welcome to SO! Check out the [tour]. There are like 4 different aspects to this question, and it seems like you've only tackled a few, so I recommended some existing questions that cover the other parts. BTW, note that in older versions of Python, dicts are unordered. – wjandrea Feb 20 '21 at 01:20
2 Answers
2
Same as Gerges' answer, but you did say that you still wanted your dictionary numerically sorted, so just a slight modification to the original answer:
d = {'z':1, 'A':1, 'a':1, 'b':3}
dict(sorted(d.items(), key=lambda x: (x[1], x[0].lower())))
# {'A': 1, 'a': 1, 'z': 1, 'b': 3}

wasiqam
- 151
- 5
1
If you don't care if things are copied around, you can try this:
d = {'z':1, 'A':1, 'a':1, 'b':3}
dict(sorted(d.items(), key=lambda x: x[0].lower()))
# {'A': 1, 'a': 1, 'b': 3, 'z': 1}

Gerges
- 6,269
- 2
- 22
- 44