Search code examples
pythondictionaryprintingformatting

How can I generalize getting values from a dictionary key?


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


Solution

  • 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'