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])
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.
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.
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.
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)
My favorite way:
import json print(json.dumps(dictionary, indent=4, sort_keys=True))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With