Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading