I wish to merge some values in a dictionary based on the conditions:
- dict keys are within +-1 of each other (1 is example, can be a different value)
- Create new dictionary with averaged key and merged values
A small workable example. Say you have value z and values belonging to that value z called ids:
#Input data
ids = [1,0,2,4,3,5,6,7,8]
z = [0,1,1,4,0,1,3,3,1]
#Rewriting in dictionary
dictionary = {}
for item_index, item in enumerate(z):
if item in dictionary:
dictionary[item].append(ids[item_index])
else:
dictionary[item] = [ids[item_index]]
#Output is now: {0: [1, 3], 1: [0, 2, 5, 8], 4: [4], 3: [6, 7]}
My desired output is based on the fact that keys +- 1 should be merged and averaged:
{0.5: [1,3,0,2,5,8], 3.5: [4,6,7]}
Sorted or not does not matter. Does someone know how to get the desired output in an efficient way? I'm really stuck.
EDIT
The +-1 is an example. I wish to be able to alter the tolerance of merging, and so it should be a variable. Furthermore, the to be merged keys are not always pairs, but can be larger groups