-3

In python, how do you pretty print a dictionary such that dictionary keys are not-case sensitive?

For example, Apple with a big letter A and apple with a small letter a will be near each-other.

The results should be printed in the same style as the following example:

d = {
     'approx'             : 'approximately' ,
     'dfrac'              : 'display fraction' ,
     'Leftrightarrow'     : 'Left and right arrow' ,
     'rangle'             : 'right angle' ,
     'vDash'              : 'vertical turnstile with double dash' ,
     'vdash'              : 'vertical turnstile with single dash' ,
     'lhd'                : 'left lazy head' ,
     'lim'                : 'limit' ,
     'xleftarrow'         : 'left arrow with parameter input' ,
     'varlimsup'          : 'variable limit supremum' ,
     'simeq'              : 'similar or equal' ,
     'iff'                : 'if and only if' ,
     'lt'                 : 'less than' ,
     'notin'              : 'not element of or in' ,
     'equiv'              : 'equivalent to' ,
     'ge'                 : 'greater than or equal' ,
     'Gamma'              : 'big uppercase Gamma' ,
     'cong'               : 'congruent' ,
     'infty'              : 'infinity' ,
     'subsetneq'          : 'subset of and not equal to' ,
     'prod'               : 'product' ,
     'varepsilon'         : 'variable epsilon' ,
     'sum'                : 'summation' ,
     'mathbb'             : 'mathematics black board bold' ,
     'le'                 : 'less than or equal to' ,
     'bar'                : 'over bar' ,
     'lbrace'             : 'left brace' ,
     'mu'                 : 'greek letter mu' ,
     'cdots'              : 'centered dots' ,
     'mp'                 : 'minus plus' ,
     'lnot'               : 'logical not' ,
     'spadesuit'          : 'spade suit symbol' ,
     'ell'                : 'script el el' ,
     'subseteq'           : 'subset or equal' ,
     'rceil'              : 'right ceiling' ,
     'vdots'              : 'vertical dots' ,
     'mapsto'             : 'maps to arrow' ,
     'genfrac'            : 'generalized fraction' ,
     'varliminf'          : 'variable limit infimum' ,
     'rVert'              : 'right vertical bar' ,
     'iint'               : 'integral integral' ,
     'iiint'              : 'integral integral integral' ,
     'lVert'              : 'left vertical bar' ,
     'ddot'               : 'double diagonal dot' ,
     'varnothing'         : 'variable nothing' ,
     'frac'               : 'fraction' ,
}

In this particular example, the inputs (keys) are LaTeX commands and the outputs (values) are English phrases with words spelled out in full such that the key is a sub-sequence formed by deleting zero or more letters from the full English phrase.

Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42

2 Answers2

1

You can use sorted and give it a key to compare the keys in lowercase. Below is a rudementary solution:

print("d = {")

for k, v in sorted(d.items(), key=lambda x: x[0].casefold()):
    print(f"\t{k!r:<20}: {v!r} ,")

print("}")
Jab
  • 26,853
  • 21
  • 75
  • 114
  • 1
    Using fstring syntax: `f'\t{k!r:<20}: {v!r},'`. – InSync May 01 '23 at 19:19
  • 1
    In general, `casefold` would be better than `lower` – chepner May 01 '23 at 19:29
  • In theory, casefold and lower aren't exactly the right approach, using either method gives you no control of the relative positioning of words in a sort. It is rare for a collation table to give identical weighting to a case distinction. At some point you want consistency around how words identical except by case are ordered. It is unfortunate that Python sorting isn't based on Unicode, were case distinctions are a tertiary difference. – Andj May 29 '23 at 14:50
-4
reps_of_keys = (repr(key).lower().strip() for key in d)

sorted_rkeys = list(sorted(reps_of_keys))

print("{")
for key in d:
    print(
            4*" ",
            repr(key).ljust(20),
            ":",
            repr(d[key]),
            ","
        )
print("}")
    
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
  • 1
    Please consider adding an explanation. – InSync May 01 '23 at 19:04
  • Is this your current solution? Did this solve your problem? What was the issue in the first place? – B Remmelzwaal May 01 '23 at 19:08
  • 5
    Sorting your keys is irrelevant here. You're only iterating on the original dictionary. – BTables May 01 '23 at 19:09
  • Perhaps it would be better to add this to your question to demonstrate your attempt rather than as an answer. – JonSG May 01 '23 at 19:17
  • @BRemmelzwaal There is a check box labeled, "share your knowledge question and answer style". The idea is that someone will type something like, "**how do I pretty print a python dictionary?**" into Google or another search engine. As long as that persons question and my question have at least 4 or 5 words in common, it is likely that my question and answer will show up in their search results. I enjoy teaching people what I know about python. I wanted to have the answer available for the next person who typed in a question similar to "**how do I pretty print a python dictionary?**" – Toothpick Anemone May 01 '23 at 19:34
  • 1
    @SamuelMuldoon Then why post this as an answer? Why not include this in your question as "this is what I've done so far", which is not only more genuine as you are not answering your question wrongfully, but allows other answers to solve the problem at hand? I am all for sharing knowledge and having the right questions surface when looking up problems, but this is **not** the way to do it. – B Remmelzwaal May 01 '23 at 19:38
  • @BTables we sorted the keys of the dictionary keys because python will not sort the dictionary keys without being told to do so. Suppose we name the input dictionary `idict`. Then, code like `for key in idict: print(key, idict[key])` will not print the dictionary sorted alphabetically. Sorting things alphabetically ensures that words with a similar sound at the beginning of the word, such as `about, actually, after, again, against, always, among, animal, another, answer, appear` – Toothpick Anemone May 01 '23 at 19:38
  • @SamuelMuldoon I understand that dictionary keys aren't ordered alphabetically. What I meant was you're sorting the keys, but then iterating on the original, unsorted, dictionary values. So what you will print will not be sorted. – BTables May 01 '23 at 19:40
  • @JonSG I would only add my answer to the question as an attempt if the code was not fully functioning and working. When my answer is fully-functioning, working, and does what it is supposed to, I check the "share my knowledge Q and A style" checkbox. – Toothpick Anemone May 01 '23 at 19:42
  • 1
    @BRemmelzwaal Answering your own question like this is most definitely a standard and proper thing to do on SO. This answer isn't correct, but the approach 100% is. – BTables May 01 '23 at 19:42
  • 3
    @SamuelMuldoon But your code is not fully functional... – JonSG May 01 '23 at 19:44