Interest in dictionaries?

dict1 = {'Milky': ['yes', 'no', 'no', 'yes', 'no'],
         'Chocolate': ['yes', 'no', 'yes', 'yes', 'no']  }  

for j in dict1:

Chocolate and Milky are the conditions (in the experiment) and 'yes'or 'no'are they the answers for each test.

I would like to calculate the percentage 'yes'in the milk state ( 2 / 5 * 100) and the state of the chocolate, but I'm not sure how to do it.

+4
source share
1 answer

I would create a percentage function:

def percentage(of, in_):
    return in_.count(of) * 100 / len(in_)

and then apply this in the understanding of the dictionary:

>>> dct = {'Milky': ['yes', 'no', 'no', 'yes', 'no'], 
...        'Chocolate': ['yes', 'no', 'yes', 'yes', 'no']}
>>>
>>> {key: percentage('yes', values) for key, values in dct.items()}
{'Chocolate': 60.0, 'Milky': 40.0}
+6
source

Source: https://habr.com/ru/post/1669000/


All Articles