Home > Enterprise >  Removing specific values from dictionary
Removing specific values from dictionary

Time:10-18

I am working on problems related to dictionaries and lists.

This is my input data

{12: [33, 1231, (40, 41), (299, 304), (564, 569), (1139, 1143), (1226, 1228)], 
 17: [9, 1492, (30, 43), (1369, 1369)], 
 20: [9, 1492, (30, 45), (295, 310), (561, 573), (927, 929), (1133, 1148), (1222, 1236), (1354, 1356), (1368, 1369)], 
 26: [34, 1364],
 27: [300, 1360, (918, 922)],
 36: [34, 1364]}

My objective is to remove key-value pair which contains only integer data type inside the list of values. (In this input data, I want to remove data such as 26: [34, 1364] and 36: [34, 1364]).

So, my output would look like this

{12: [33, 1231, (40, 41), (299, 304), (564, 569), (1139, 1143), (1226, 1228)], 
 17: [9, 1492, (30, 43), (1369, 1369)], 
 20: [9, 1492, (30, 45), (295, 310), (561, 573), (927, 929), (1133, 1148), (1222, 1236), (1354, 1356), (1368, 1369)], 
 27: [300, 1360, (918, 922)]}

What is the most efficient method to solve this problem.

CodePudding user response:

Use all:

data = {k: v for k, v in data.items() if not all(isinstance(x, int) for x in v)}

You could be more fanciful, using map and the dunder method:

data = {k: v for k, v in data.items() if not all(map(int.__instancecheck__, v))}

CodePudding user response:

Use a dictionary comprehension with not isinstance(..., int):

{k: v for k, v in dct.items() if any(not isinstance(i, int) for i in v)}

Output:

{12: [33, 1231, (40, 41), (299, 304), (564, 569), (1139, 1143), (1226, 1228)],
 17: [9, 1492, (30, 43), (1369, 1369)],
 20: [9, 1492, (30, 45), (295, 310), (561, 573), (927, 929), (1133, 1148), (1222, 1236), (1354, 1356), (1368, 1369)],
 27: [300, 1360, (918, 922)]}
  • Related