I have a list of dictionaries such as:
[ {'Type': 'Water', 'Level': '8'}, {'Type': 'Fire', 'Level': '2'}, {'Type': 'Fire', 'Level': '8'}, ... ]
I have this code that basically prints it as a table:
my_list_of_dics = [ {'Type': 'Water', 'Level': '8'}, {'Type': 'Fire', 'Level': '2'}, {'Type': 'Fire', 'Level': '8'}]
#Initialize string
string_table = ""
#Print headers
for key in my_list_of_dics[0]:
string_table = key "\t"
#Jump line
string_table = "\n"
#Print values (rows), matching the header order and tabulations between each value and jump a line after each row
for row in my_list_of_dics:
string_table = row['Type'] "\t" row['Level'] "\n"
print(string_table)
Prints this:
Type Level Water 8 Fire 2 Fire 8
It works as I want it, however I have to hardcode the names of the keys and the number of tabulations ( "\t") between each when printing it out.
Generating the headers of the table is fortunately generalized, however I haven't beeen able to generalize the printing key's values and the number of tabulations (as seen in my 2nd loop).
CodePudding user response:
If all the dictionaries have the same keys, you can replace the line of code in your for
loop with:
string_table = '\t'.join(row[key] for key in my_list_of_dics[0]) '\n'
Note you can optimise this by defining
keys = list(my_list_of_dics[0].keys())
then you can just use
string_table = '\t'.join(row[key] for key in keys) '\n'
and you can make the first line of the table with
string_table = '\t'.join(keys) '\n'
CodePudding user response:
You can use python format
to create tables.
my_list_of_dics = [
{"Type": "Water", "Level": "8"},
{"Type": "Fire", "Level": "2"},
{"Type": "Fire", "Level": "8"},
]
print("{:<10} {:<10}".format("Type", "Level"))
for val in my_list_of_dics:
print("{:<10} {:<10}".format(val["Type"], val["Level"]))
will give us
Type Level
Water 8
Fire 2
Fire 8
More generalized form
my_list_of_dics = [
{"Type": "Water", "Level": "8"},
{"Type": "Fire", "Level": "2"},
{"Type": "Fire", "Level": "8"},
]
get_keys = list(my_list_of_dics[0].keys())
fmt = "{:<10}" * len(get_keys)
print(fmt.format(*get_keys))
for val in my_list_of_dics:
print(fmt.format(*val.values()))