Home > Enterprise >  Removing nested list in a dictionary
Removing nested list in a dictionary

Time:10-22

This is my input data.

data = {323: [[639, 646]], 325: [[1491, 1507]], 332: [[639, 647], [823, 833], [1274, 1298]], 334: [[640, 646]], 335: [[822, 834]]}

I want to remove the sublist whose values are lesser than or equal to 10.

My output would look like this.

output_data = {323: [], 325:[[1491,1507]], 332:[[1274,1298]], 334:[], 335:[[822,834]]}

How can I achieve the desired output?

CodePudding user response:

You can write a list comprehension that re-builds the list of lists for each key in the dictionary, with a conditional that the difference of the items in the inner is greater than 10:

for key, values in data.items():
    data[key] = [[low, high] for low, high in values if high - low > 10]

CodePudding user response:

I just did a quick test, and looks like it's possible to do this using a dict comprehension and the filter buitin function:

result = {k: list(filter(lambda v: v[1] - v[0] > 10, val_list))
          for k, val_list in data.items()}

print(result)

Output:

{323: [], 325: [[1491, 1507]], 332: [[1274, 1298]], 334: [], 335: [[822, 834]]}

Assumption: The sublists are sorted with lowest element first, and then higher element next. If not, you'll need to wrap it with an abs call, like abs(v[1] - v[0]) to be safe, in case v[0] is the higher element.

  • Related