How do i print a formatted dictionary in python?

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])

How do i print a formatted dictionary in python?

codeforester

35.5k15 gold badges99 silver badges125 bronze badges

asked Jun 22, 2017 at 3:17

How do i print a formatted dictionary in python?

Raphael HuangRaphael Huang

1,2032 gold badges7 silver badges5 bronze badges

3

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)

answered Jun 22, 2017 at 4:25

4

My favorite way:

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

answered Jun 22, 2017 at 3:26

Ofer SadanOfer Sadan

10.6k4 gold badges33 silver badges58 bronze badges

4

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])))

answered Jun 22, 2017 at 3:22

How do i print a formatted dictionary in python?

sudosudo

5,2035 gold badges38 silver badges74 bronze badges

2

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': [],
  },
}

Simon

5,2046 gold badges47 silver badges82 bronze badges

answered Nov 3, 2019 at 9:20

How do i print a formatted dictionary in python?

dtardtar

1,30911 silver badges16 bronze badges

1

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))

answered Dec 15, 2019 at 9:00

How do i print a formatted dictionary in python?

Shital ShahShital Shah

57.7k12 gold badges223 silver badges180 bronze badges

1

I wrote this function to print simple dictionaries:

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

adiga

32.2k8 gold badges55 silver badges78 bronze badges

answered Jul 3, 2019 at 10:10

How do i print a formatted dictionary in python?

NautilusNautilus

1802 silver badges6 bronze badges

1

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]))

adiga

32.2k8 gold badges55 silver badges78 bronze badges

answered Jun 22, 2017 at 3:33

How do i print a formatted dictionary in python?

I did create function (in Python 3):

def print_dict(dict):
    print(

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

    )

answered Dec 31, 2021 at 9:07

How do i print a formatted dictionary in 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'}))

answered Apr 25 at 15:29

JohnJohn

9368 silver badges16 bronze badges

Not the answer you're looking for? Browse other questions tagged python or ask your own question.

How do you print a dictionary structure in Python?

Use pprint() to Pretty Print a Dictionary in Python Within the pprint module there is a function with the same name pprint() , which is the function used to pretty-print the given string or object. First, declare an array of dictionaries. Afterward, pretty print it using the function pprint.

Can I print a dictionary in Python?

You can print a dictionary in Python using either for loops or the json module. The for loop approach is best if you want to display the contents of a dictionary to a console whereas the json module approach is more appropriate for developer use cases.

How do you print a formatted table in Python?

How to Print Table in Python?.
Using format() function to print dict and lists..
Using tabulate() function to print dict and lists..
texttable..
beautifultable..
PrettyTable..

How do I print a dictionary object?

Print a dictionary line by line using for loop & dict. items() dict. items() returns an iterable view object of the dictionary that we can use to iterate over the contents of the dictionary, i.e. key-value pairs in the dictionary and print them line by line i.e.