Reputation: 352
I have a dict
with tuples as key, like:
my_dict = {('A1', 'A2'): 0.6, ('A1', 'A1'): 1, ('A2', 'A2'): 1, ('A2', 'A1'): 0.3}
I want to print a table like:
Table A1 A2
A1 1 0.6
A2 0.3 1
How to deal with this problem without using Pandas? I just don't want to import modules that are not built into python.
Upvotes: 1
Views: 133
Reputation: 71451
You can use a list comprehension:
my_dict = {('A1', 'A2'): 0.6, ('A1', 'A1'): 1, ('A2', 'A2'): 1, ('A2', 'A1'): 0.3}
table = [[[c for [d1, d2], c in my_dict.items() if f'A{i}' == d2 and f'A{b}' == d1][0]
for i in range(1, 3)] for b in range(1, 3)]
top = 'table {}'.format(' '.join(f'A{i}' for i in range(1, len(max(table, key=len))+1)))
final = '{}\n{}'.format(top, '\n'.join(f'A{i} {" ".join(map(str, a))}' for i, a in enumerate(table)))
Output:
table A1 A2
A0 1 0.6
A1 0.3 1
Upvotes: 0
Reputation: 343
A more general solution, avoiding hardcode and filling "NA" for missing data:
my_dict = {('A1', 'A2'): 0.6, ('A3', 'A1'): 1, ('A2', 'A2'): 1, ('A2', 'A1'): 0.3}
labs = []
for key in my_dict.keys():
for k in key:
if k not in labs:
labs.append(k)
labs = sorted(labs)
print("Table\t" + "\t\t".join(labs))
for i in labs:
print(i, end="\t\t")
for j in labs:
try:
print(my_dict[(i, j)], end="\t\t")
except KeyError:
print("NA", end="\t\t")
print()
Table A1 A2 A3
A1 NA 0.6 NA
A2 0.3 1 NA
A3 1 NA NA
Upvotes: 1
Reputation: 3198
print("Table A1 A2")
for i in ['A1','A2']:
print(i, end= " ")
for j in ['A1','A2']:
print(my_dict[(i,j)], end = " ")
print()
Output
Table A1 A2
A1 1 0.6
A2 0.3 1
Upvotes: 0