0

So I have a dictionary, say:

myDict = {"145":1, "Kittens":2, "apples":1, "trees":2}

and using pprint(myDict, ...), I get:

{'145': 1,
 'Kittens': 2,
 'apples': 1,
 'trees': 2}

Instead, I'd like to ignore the capital K's apparent order priority and get:

{'145': 1,
 'apples': 1,
 'Kittens': 2,
 'trees': 2}

Do I have to use the PrettyPrinter module? Is there a hidden pprint argument? Or is there another solution entirely? My dict keys aren't any more complicated than this. Thanks.

Luke McPuke
  • 354
  • 1
  • 2
  • 12
  • 3
    You can not order a dictionary (only in some versions of Python-3.6). You should use an `OrderedDict`. – Willem Van Onsem Jul 21 '17 at 19:46
  • 1
    @WillemVanOnsem Certainly. However, `pprint.pprint` orders the keys when you print a dict, as mentioned in [the docs](https://docs.python.org/2/library/pprint.html) – PM 2Ring Jul 21 '17 at 20:02
  • 2
    And to the best of my knowledge has no provision for custom sorting. – cs95 Jul 21 '17 at 20:08

1 Answers1

2

Without imports, simple version:

def printdict(myDict):
    print('{')
    for a,b in sorted(myDict.items(),key = lambda tuple : tuple[0].lower()):
        print("'"+str(a)+"'"+" : "+str(b))
    print('}')

Improved version according to PM 2Ring ( this will work for anything ):

def printdict(myDict):
    print('{')
    for a,b in sorted(myDict.items(),key = lambda t : t[0].lower()):
        print(' {!r}: {!r},'.format(a, b))
    print('}')
Ruan
  • 772
  • 4
  • 13
  • This worked rather nicely for my actual input. I haven't used too many one-line lambda statements, so I'm going to try and figure out what's going on here. Also have to figure out how to now write this to a new .txt file! Thank you for your help. – Luke McPuke Jul 21 '17 at 21:05
  • 1
    Read print() function documentation. It supports a ",file=open("file.txt","a")" argument. So you can use print() to print to a file instead of stdout. – Ruan Jul 21 '17 at 21:41
  • 1
    It's not a good idea to use `tuple` as a variable name, as that shadows the built-in `tuple` type. It won't hurt here, since it's just a local name in the lambda, but IMHO it's still a bit confusing. FWIW, I'd use `tup` or even just `t` in that situation. – PM 2Ring Jul 22 '17 at 07:51
  • 1
    Also, your inner `print` call can be improved. Currently, it won't work properly if `a` contains a quote (which hopefully will never happen, but still), and it will fail if `b` happens to be a string. Generally, you should let `print` or `format` do string conversions for you. Here's an improved version: `print(' {!r}: {!r},'.format(a, b))`. The `!r` say to use the object's `__repr__`, so strings will automatically get quoted properly. – PM 2Ring Jul 22 '17 at 07:52