Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print out a dictionary nicely in Python?

Tags:

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]) 
like image 419
Raphael Huang Avatar asked Jun 22 '17 03:06

Raphael Huang


People also ask

How do you format a dictionary in Python?

Use format() function to format dictionary print in Python. Its in-built String function is used for the purpose of formatting strings according to the position. Python Dictionary can also be passed to format() function as a value to be formatted.

How do you print a dictionary value?

To print Dictionary values, use a for loop to traverse through the dictionary values using dict. values() iterator, and call print() function. In the following program, we shall initialize a dictionary and print the dictionary's values using a Python For Loop.

How do you print a dictionary without brackets in Python?

You can use slicing on the string representation of a dictionary to access all characters except the first and last ones—that are the curly bracket characters. For example, the expression print(str({'a': 1, 'b': 2})[1:-1]) prints the list as 'a': 1, 'b': 2 without enclosing brackets.


2 Answers

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) 
like image 170
foslock Avatar answered Sep 19 '22 22:09

foslock


My favorite way:

import json print(json.dumps(dictionary, indent=4, sort_keys=True)) 
like image 31
Ofer Sadan Avatar answered Sep 18 '22 22:09

Ofer Sadan