Given the following dictionary:
dict_sports = {'Skateboarding': 163,
'Bowling': 134,
'Rugby': 83,
'Wrestling': 57,
'Baseball': 30,
'Badminton': 24,
'Volleyball': 22,
'Basketball': 18,
'Football': 16,
'Weightlifting': 15,
'Golf': 14,
'Skiing': 10,
'Boxing': 8,
'Cricket': 6}
total_sum = sum([v for k,v in dict_sports.items()])
print(total_sum)
I want to split the dictionary into 3 smaller dictionaries; so that the following condition is met:
The three dictionaries' total sum of their respective values; should be near a certain threshold; say within a percentage plus/minus %2.5 of 200.
i.e. Total sum of each dictionary's values should be:
195 <= total_sum <= 205
Here is my solution, which solves my original problem, but still contradicts the condition I put above, which could be because of the data itself (cannot be split with that accuracy)... My problem is not with the accuracy of the split; my problem is with the amount of coding I have to do for this simple task!
list_01 = []
list_02 = []
list_03 = []
dict_01 = {}
dict_02 = {}
dict_03 = {}
for k,v in dict_sports.items():
if (sum(list_01) < 195) and (k not in dict_02) and (k not in dict_03):
list_01.append(v)
dict_01[k] = v
if sum(list_01) > 205:
list_01.pop()
dict_01.pop(k, None)
print(sum(list_01))
for k,v in dict_sports.items():
if (sum(list_02) < 195) and (k not in dict_01) and (k not in dict_03):
list_02.append(v)
dict_02[k] = v
if sum(list_02) > 205:
list_02.pop()
dict_02.pop(k, None)
print(sum(list_02))
for k,v in dict_sports.items():
if (sum(list_03) < 195) and (k not in dict_01) and (k not in dict_02):
list_03.append(v)
dict_03[k] = v
if sum(list_03) > 205:
list_03.pop()
dict_03.pop(k, None)
print(sum(list_03))
print(dict_01)
print(dict_02)
print(dict_03)
I would imagine that there is a much better way to approach this problem, maybe with pandas, or any other python library or a third-party library; or a better code than this!