Reputation: 45
I have the following collection that holds a dictionary:
{'EHAM': [78, [55, 23]], 'EGLL': [67, [46, 21]], 'LOWW': [67, [44, 23]], 'LFPG': [75, [43, 32]]}
I'd like to print the collection in the following output data format:
NAME #TOTAL #TK #LA
EHAM 78 55 23
EGLL 67 46 21
LOWW 67 44 23
LFPG 75 43 32
Right now I'm getting the following ouput:
#NAME #TOTAL #TK #LA
EHAM [78, [55, 23]]
EGLL [67, [46, 21]]
LOWW [67, [44, 23]]
LFPG [75, [43, 32]]
This is the piece of code I'm using:
#print(topAirpots_dict)
print("\n#NAME"+ " #TOTAL"+ " #TK"+ " #LA\n")
for k in (top_dict):
print(k,top_dict[k])
Upvotes: 0
Views: 57
Reputation: 21
This may be helpful:
my_dict = {'EHAM': [78, [55, 23]], 'EGLL': [67, [46, 21]], 'LOWW': [67, [44, 23]], 'LFPG': [75, [43, 32]]}
print("NAME", "#TOTAL", "#TK", "#LA", sep="\t\t")
for k, item in my_dict.items():
total, other = item
tk, tl = other
print(f"{k} {total:>10} {tk:>10} {tl:>7}")
Output:
NAME #TOTAL #TK #LA
EHAM 78 55 23
EGLL 67 46 21
LOWW 67 44 23
LFPG 75 43 32
used
string formatting-> [https://www.geeksforgeeks.org/python-format-function/] &
string interpolation-> [https://realpython.com/python-string-formatting/]
Upvotes: 0
Reputation: 672
Might not be the most performant way but gives the wanted output:
print("\nNAME"+ " \t#TOTAL"+ " \t#TK"+ " \t#LA\n")
for k in (top_dict):
first_val = top_dict[k][0]
sec_val = top_dict[k][1][0]
third_val = top_dict[k][1][1]
print(k , " \t" , first_val , " \t" , sec_val , " \t" , third_val)
or faster but a bit harder to read:
print("\nNAME"+ " \t#TOTAL"+ " \t#TK"+ " \t#LA\n")
for k in (top_dict):
print(k , " \t" , top_dict[k][0], " \t" , top_dict[k][1][0], " \t" , top_dict[k][1][1])
Upvotes: 0
Reputation: 728
If the number of elements in the list inside values of the dictionary doesn't change, the following solution works.
print("\n#NAME"+ " #TOTAL"+ " #TK"+ " #LA\n")
for k in (top_dict):
print(k, top_dict[k][0], top_dict[k][1][0], top_dict[k][1][1])
Upvotes: 2