I want to merge values depending on their key
d1 = {"300":["index1","index2"],"301":["index9","index10"],"400":["index12","index13"]
I want to merge the values for the keys that are within the range of 10 so like 300 merge with 301 because 301 is bigger than 300 by 1 but 301 wont go with 400 because 400 is bigger than both of them over 10 but if we also had 410 we would merge it with 400 because its exactly 10 from the 400 so anything less than or equal to 10 that range everything in it gets merged
This post makes no sense and I dont know how to explain it
CodePudding user response:
from itertools import chain
d1 = {"300":["index1","index2"],"301":["index9","index10"],"400":["index12","index13"], "410":["index14","index15"]}
# the split function is found here. [split function][1]
def split(arr, k):
arr = [int(e) for e in arr]
out = []
for i in sorted(arr):
if not out:
out = [[i]]
continue
if out[-1] and i-out[-1][0] <= k: # use <= to accept equality
out[-1].append(i)
else:
out.append([i])
return out
d = {}
# for each sublist of divided keys find the corresponding values, and save to a new dictionary
for lst in split(d1,10):
d[' '.join(map(str,lst))] = list(chain(*[d1.get(str(k)) for k in lst]))
print(d)
{'300 301': ['index1', 'index2', 'index9', 'index10'], '400 410': ['index12', 'index13', 'index14', 'index15']}
[1]: https:// https://stackoverflow.com/questions/71965420/divide-a-list-into-sublists-such-that-difference-between-any-2-elements-in-a-sub