How to add values accordingly of the first indices of a dictionary of tuples of a list of strings? Python 3x
Posted
by
TheStruggler
on Stack Overflow
See other posts from Stack Overflow
or by TheStruggler
Published on 2012-11-26T22:57:37Z
Indexed on
2012/11/26
23:03 UTC
Read the original article
Hit count: 161
I'm stuck on how to formulate this problem properly and the following is:
What if we had the following values:
{('A','B','C','D'):3,
('A','C','B','D'):2,
('B','D','C','A'):4,
('D','C','B','A'):3,
('C','B','A','D'):1,
('C','D','A','B'):1}
When we sum up the first place values: [5,4,2,3] (5 people picked for A first, 4 people picked for B first, and so on like A = 5, B = 4, C = 2, D = 3)
The maximum values for any alphabet is 5, which isn't a majority (5/14 is less than half), where 14 is the sum of total values.
So we remove the alphabet with the fewest first place picks. Which in this case is C.
I want to return a dictionary where {'A':5, 'B':4, 'C':2, 'D':3}
without importing anything.
This is my work:
def popular(letter):
'''(dict of {tuple of (str, str, str, str): int}) -> dict of {str:int}
'''
my_dictionary = {}
counter = 0
for (alphabet, picks) in letter.items():
if (alphabet[0]):
my_dictionary[alphabet[0]] = picks
else:
my_dictionary[alphabet[0]] = counter
return my_dictionary
This returns duplicate of keys which I cannot get rid of.
Thanks.
© Stack Overflow or respective owner