1

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%)
MBasith
  • 1,407
  • 4
  • 29
  • 48

1 Answers1

1

Here's one option:

from collections import namedtuple                                         

trained = {'Dog': 4, 'Cat': 3, 'Bird': 1, 'Fish': 12, 'Mouse': 19}         
untrained = {'Cat': 2, 'Mouse': 7, 'Dog': 4}                               

Score = namedtuple('Score', ('total', 'percent', 'name'))                  

trained_scores = []                                                        
for t in trained:                                                          
    trained_scores.append(                                                 
        Score(total=trained[t],                                            
              percent=(trained[t]/(trained[t]+untrained.get(t, 0)))*100,   
              name=t)                                                      
    )                                                                      

untrained_scores = []                                                      
for t in untrained:                                                        
    untrained_scores.append(                                               
        Score(total=untrained[t],                                          
              percent=(untrained[t]/(untrained[t]+trained.get(t, 0)))*100, 
              name=t)                                                      
    )                                                                      

trained_scores.sort(reverse=True)                                          
untrained_scores.sort(reverse=True)                                        
import pprint; pprint.pprint(trained_scores)                               
import pprint; pprint.pprint(untrained_scores)

# I might name these something different.
row_template = '{:<30} {:<30}'                                          
item_template = '{0.name:<10} {0.total:>3} ({0.percent:>6.2f}%)'        
print('='*61)                                                           
print(row_template.format('Trained', 'Untrained'))                      
print('='*61)   

for trained, untrained in zip_longest(trained_scores, untrained_scores):
    print(row_template.format(                                          
        '' if trained is None else item_template.format(trained),       
        '' if untrained is None else item_template.format(untrained),   
    ))                                                                  

Outputs:

=============================================================
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%)                                     
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
  • Thanks that is much cleaner but I am still looking to see if I can get the printout of values and percentages in one table. – MBasith Aug 11 '16 at 14:54
  • @MBasith hows that? – Wayne Werner Aug 11 '16 at 14:57
  • Wow! Yes, that precisely accomplishes what I had envisioned. I am a beginner and do not understand much of the logic here at first glance but will try to digest it slowly. Thanks for the feedback and help. Greatly appreciated. (Bow). – MBasith Aug 11 '16 at 15:51
  • Hi I had a chance to review the code I think I have grasped most of it. Having difficult on why you have the "if" statements with "None else" statements. Can you please explain the last block of code? – MBasith Aug 11 '16 at 18:11
  • These are called [ternary statements or conditional expressions](https://www.python.org/dev/peps/pep-0308/). There are some good explanations found http://stackoverflow.com/q/394809/344286 and finally, I'd recommend using the REPL to experiment with code snippets you don't fully understand. It's extremely useful :) – Wayne Werner Aug 11 '16 at 19:08
  • @ Wayne Werner Thanks! Those were great resources. Appreciate all the help. – MBasith Aug 11 '16 at 20:15