Reputation: 607
I have a dictionary with varying number of items. Each item can have a value of either a 1
or 0
. Those with a value of 1
are stored in a list and counted. This is then used to calculate a percentage which would then be used to replace the value 1
.
For example: if I have 10 items and only 7 contain a value of 1
, the calculated percentage would be 100 / 7 = 14
. Therefore those 7 items will have a new value of 14
.
But there is a remainder left over and what I would like is for some items to gain this remainder (so 5 items would have a value of 14
, 2 items would have a value of 15
so that (5 * 14) + (2 * 15) = 100
.
How could this be done?
This is the code I used which gets the percentage value but I am unsure how to implement the remainder part (I would like to only show integers in the dictionary):
someDict = {
'item_01': 0,
'item_02': 0,
'item_03': 0,
'item_04': 1,
'item_05': 1,
'item_06': 1,
'item_07': 1,
'item_08': 1,
'item_09': 1,
'item_010': 1
}
percentage_list = []
for key, value in someDict.items():
if value == 1:
percentage_list.append(value)
percentage_value = int(100) / int(len(percentage_list))
# =98
# Replace all 1's in someDict with percentage value
for key, value in someDict.items():
if value == 1:
someDict[key] = percentage_value
Upvotes: 0
Views: 221
Reputation: 1238
If for some reason your remainder left over is such that each element may gain more than 1
, just after calculating percentage_value
:
num_divisions = len(percentage_list)
remainder = 100 - percentage_value * num_divisions
# Replace all 1's in someDict with percentage value
for i, key in enumerate(filter(lambda k: someDict[k] == 1, someDict)):
extra = int(remainder/(num_divisions - i))
someDict[key] = percentage_value + extra
remainder -= extra
Upvotes: 2
Reputation: 5078
You should use // for int division and % for the remainder:
someDict = {
'item_01': 0,
'item_02': 0,
'item_03': 0,
'item_04': 1,
'item_05': 1,
'item_06': 1,
'item_07': 1,
'item_08': 1,
'item_09': 1,
'item_010': 1
}
percentage_list = []
for key, value in someDict.items():
if value == 1:
percentage_list.append(value)
percentage_value = 100 // len(percentage_list)
remainder_value = 100 % len(percentage_list)
# Replace all 1's in someDict with percentage value
for key, value in someDict.items():
if value == 1:
if remainder_value > 0:
someDict[key] = percentage_value + 1
remainder_value -= 1
else:
someDict[key] = percentage_value
print(someDict)
Upvotes: 3