I am new to Python and am trying to perform counts and calculations by comparing two dictionaries but having trouble presenting it together. Is there a way to perform the below during my first iteration of printing the keys and values together?
I would like to:
1.) Check if a key in dictionary x is in dictionary y
2.) If key exists divide the key value by total key values from both dictionaries and print a percentage next to the value
3.) If the key does NOT exist divide the key by itself and print a percentage next to the value
I am able to accomplish the two separately but not together. Also if you have suggestions for improving my code efficiency it would be greatly appreciated.
Code:
import operator, itertools
trained = {'Dog': 4, 'Cat': 3, 'Bird': 1, 'Fish': 12, 'Mouse': 19}
untrained = {'Cat': 2, 'Mouse': 7, 'Dog': 4}
trained_list = []
untrained_list = []
print('='* 40)
print('Trained \t Untrained')
print('='* 40)
for k, v in sorted(trained.items(), key=operator.itemgetter(1), reverse=True):
t = (k, v )
trained_list.append(t)
for k, v in sorted(untrained.items(), key=operator.itemgetter(1), reverse=True):
u = (k, v )
untrained_list.append(u)
for x, y in itertools.zip_longest(trained_list, untrained_list, fillvalue=" "):
print(str(x[0]).ljust(5, ' ') + '\t' + str(x[1]) + '\t', y[0] + '\t' + str(y[1]))
print('=' * 30)
for k,v in untrained.items():
if k in trained:
print('Untrained ' + str(k).ljust(5, ' ') + '\t\t' + ('{0:.2f}%').format((untrained[k]/(untrained[k] + trained[k])*100)))
print('=' * 30)
for k, v in trained.items():
if k in untrained:
print('Trained ' + str(k).ljust(5, ' ') + '\t\t' + ('{0:.2f}%').format((trained[k]/(untrained[k] + trained[k]))*100))
else:
print('Trained ' + str(k).ljust(5, ' ') + '\t\t' + ('{0:.2f}%').format((trained[k] / (trained[k])) * 100))
Current Output:
========================================
Trained Untrained
========================================
Mouse 19 Mouse 7
Fish 12 Dog 4
Dog 4 Cat 2
Cat 3
Bird 1
==============================
Untrained Mouse 26.92%
Untrained Cat 40.00%
Untrained Dog 50.00%
==============================
Trained Fish 100.00%
Trained Bird 100.00%
Trained Cat 60.00%
Trained Dog 50.00%
Trained Mouse 73.08%
Desired Output:
========================================
Trained Untrained
========================================
Mouse 19 (73.08%) Mouse 7 (26.92%)
Fish 12 (100.00%) Dog 4 (50.00%)
Dog 4 (50.00%) Cat 2 (40.00%)
Cat 3 (60.00%)
Bird 1 (100.00%)