PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 16, 2022

[FIXED] How can I generalize getting values from a dictionary key?

 September 16, 2022     dictionary, formatting, printing, python     No comments   

Issue

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'


Answered By - Nick
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing