I have a nested dictionary of defaultdict(dict)
whose sub dict have int
keys and list
s (list of int
s) as values,
'A' = {2092: [1573], 2093: [1576, 1575], 2095: [1577], 2097: [1574]}
'B' = {2098: [1], 2099: [2, 3], 2101: [4], 2102: [5]}
'C' = {2001: [6], 2003: [7, 8], 2008: [9], 2009: [10]}
I want to continuously join two sub key values (lists) if their corresponding sub keys are consecutive meaning their difference is less than or equal to a pre-defined distance, e.g. the difference between two consecutive keys are less than or equal to 2 or 3, ... e.g. when setting the distance to 2, and put the joined lists into another list, this last list will look like,
[1573, 1576, 1575, 1577, 1574]
[1, 2, 3, 4, 5]
[6, 7, 8]
[9, 10]
For A
, 2092
, 2093
, 2095
, 2097
are consecutive, since their differences are <= 2, then their values are put into one list [1573, 1576, 1575, 1577, 1574]
. For C
, 2001
and 2003
are joined into [6,7,8]
since their difference is 2
, 2003
and 2008
are not joined, since their difference is 5
.
based on Detecting consecutive integers in a list
The following code can only work when the difference between two keys is 1
.
results = []
for key, sub_dict in d.items():
sub_dict_keys = sorted(sub_dict.keys())
for k, g in groupby(enumerate(sub_dict_keys), lambda ix: ix[0] - ix[1]):
consecutive_keys = list(map(itemgetter(1), g))
val_list = []
for dict_key in consecutive_keys:
val_list.extend(sub_dict[dict_key])
results.append(val_list)
print(results)
I am wondering how to make the code account for an arbitrary distance.