I am still pretty new to Python and am trying to automate something I do manually. I have a sorted dictionary consisting of 6 items. The size of the dictionary will always contain 6 items, where the key is a string and value is a float.
Once I have populated my dictionary, I want to subtract the values from the dictionary in pairs i.e value from 2nd item subtracts value from first item, value from 4th item subtracts value from 3rd item and finally value from our last item in the dictionary subtracts the value from our 5th item.
When done, I print out the results.
An example of my dictionary:
my_dict = {}
my_dict = {'item1': '18.6798', 'item2': '12.638', 'item3': '20', \
'item4': '60.00', 'item5': '65.7668', 'item6': '45.7668'}
I have been looking through dictionary comprehension in python, for loops with nested ifs (not ideal) but having trouble figuring this out. Any pointers in different ways (more efficient) that would allow me to access the index of a value within the dictionary?
remainder = {}
for key, value in sorted(my_dict.items()):
...
print(remainder)
Once I've calculated the difference between the values, I'll store them in another dictionary which I can access by key/value.
OK, I first divide them into pairs, and then for each pair I calculate the new value, and put in remainder
:
my_dict = {'item1': 18.6798, 'item2': 12.638, 'item3': 20, \
'item4': 60.00, 'item5': 65.7668, 'item6': 45.7668}
items = list(sorted(my_dict.keys()))
pairs = [items[i:i + 2] for i in range(0, len(items), 2)]
remainder = {}
for item1, item2 in pairs:
remainder[item1] = my_dict[item1] - my_dict[item2]
print(remainder)