How to print out a dictionary nicely in Python?

Python

Python Problem Overview


I've just started to learn python and I'm building a text game. I want an inventory system, but I can't seem to print out the dictionary without it looking ugly.

This is what I have so far:

def inventory():
    for numberofitems in len(inventory_content.keys()):
        inventory_things = list(inventory_content.keys())
        inventory_amounts = list(inventory_content.values())
        print(inventory_things[numberofitems])

Python Solutions


Solution 1 - Python

I like the pprint module (Pretty Print) included in Python. It can be used to either print the object, or format a nice string version of it.

import pprint

# Prints the nicely formatted dictionary
pprint.pprint(dictionary)

# Sets 'pretty_dict_str' to the formatted string value
pretty_dict_str = pprint.pformat(dictionary)

But it sounds like you are printing out an inventory, which users will likely want shown as something more like the following:

def print_inventory(dct):
    print("Items held:")
    for item, amount in dct.items():  # dct.iteritems() in Python 2
        print("{} ({})".format(item, amount))

inventory = {
    "shovels": 3,
    "sticks": 2,
    "dogs": 1,
}

print_inventory(inventory)

which prints:

Items held:
shovels (3)
sticks (2)
dogs (1)

Solution 2 - Python

My favorite way:

import json
print(json.dumps(dictionary, indent=4, sort_keys=True))

Solution 3 - Python

Here's the one-liner I'd use. (Edit: works for things that aren't JSON-serializable too)

print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items()))

Explanation: This iterates through the keys and values of the dictionary, creating a formatted string like key + tab + value for each. And "\n".join(... puts newlines between all those strings, forming a new string.

Example:

>>> dictionary = {1: 2, 4: 5, "foo": "bar"}
>>> print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items()))
1	2
4	5
foo	bar
>>>

Edit 2: Here's a sorted version.

"\n".join("{}\t{}".format(k, v) for k, v in sorted(dictionary.items(), key=lambda t: str(t[0])))

Solution 4 - Python

I would suggest to use beeprint instead of pprint.

Examples:

pprint

{'entities': {'hashtags': [],
              'urls': [{'display_url': 'github.com/panyanyany/beeprint',
                        'indices': [107, 126],
                        'url': 'https://github.com/panyanyany/beeprint'}],
              'user_mentions': []}}

beeprint

{
  'entities': {
    'hashtags': [],
    'urls': [
      {
        'display_url': 'github.com/panyanyany/beeprint',
        'indices': [107, 126],
        'url': 'https://github.com/panyanyany/beeprint'}],
      },
    ],
    'user_mentions': [],
  },
}

Solution 5 - Python

Yaml is typically much more readable, especially if you have complicated nested objects, hierarchies, nested dictionaries etc:

First make sure you have pyyaml module:

pip install pyyaml

Then,

import yaml
print(yaml.dump(my_dict))

Solution 6 - Python

Agree, "nicely" is very subjective. See if this helps, which I have been using to debug dict

for i in inventory_things.keys():
    logger.info('Key_Name:"{kn}", Key_Value:"{kv}"'.format(kn=i, kv=inventory_things[i]))

Solution 7 - Python

I wrote this function to print simple dictionaries:

def dictToString(dict):
  return str(dict).replace(', ','\r\n').replace("u'","").replace("'","")[1:-1]

Solution 8 - Python

I did create function (in Python 3):

def print_dict(dict):
    print(

    str(dict)
    .replace(', ', '\n')
    .replace(': ', ':\t')
    .replace('{', '')
    .replace('}', '')

    )

Solution 9 - Python

Maybe it doesn't fit all the needs but I just tried this and it got a nice formatted output So just convert the dictionary to Dataframe and that's pretty much all

pd.DataFrame(your_dic.items())

You can also define columns to assist even more the readability

pd.DataFrame(your_dic.items(),columns={'Value','key'})

So just give a try :

print(pd.DataFrame(your_dic.items(),columns={'Value','key'}))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRaphael HuangView Question on Stackoverflow
Solution 1 - PythonfoslockView Answer on Stackoverflow
Solution 2 - PythonOfer SadanView Answer on Stackoverflow
Solution 3 - PythonsudoView Answer on Stackoverflow
Solution 4 - PythondtarView Answer on Stackoverflow
Solution 5 - PythonShital ShahView Answer on Stackoverflow
Solution 6 - PythonBalaji NarayanaswamyView Answer on Stackoverflow
Solution 7 - PythonNautilusView Answer on Stackoverflow
Solution 8 - PythonSebastian ChetroniView Answer on Stackoverflow
Solution 9 - PythonJohnView Answer on Stackoverflow