Home > Software engineering >  Remove a list from dictionary value lists using filter() in Python3
Remove a list from dictionary value lists using filter() in Python3

Time:11-08

I have a dictionary where its key: str and value: list. I want to remove a certain list from its value lists when the key equals to a certain value and one element inside that list equal to a certain value.

For example, when d["A"]=[[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 3242413, "NEW"], [1982, "PEAR", 1299021, "OLD"]]", I want to remove the list from d["A"] where its 2nd index value equals to 3242413 so that the new dictionary at key A becomes: d["A"]=[[0, "APPLE", 1202021, "NEW"], [1982, "PEAR", 1299021, "OLD"]]".

So far I tried using filter() and dict comprehension but could not come up with a clean way to do it. Of course there's always a way to loop and remove, but I wonder if we could achieve the same thing using filter()? Something like :

# d is the dictionary key: str value: list of lists
d["A"] = [[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 3242413, "NEW"], [1982, "PEAR", 1299021, "OLD"]]

# 1. use filter
new_dict = dict(filter(lambda elem: elem[1].. != ,d.items()))  # filter out those element inside list value does not equal to 3242413

# 2. use dict comprehension
new_dict = {key: value for (key, value) in d.items() if value ... ==  }

# so the new dict becomes
d["A"]=[[0, "APPLE", 1202021, "NEW"], [1982, "PEAR", 1299021, "OLD"]]

CodePudding user response:

You're almost there with the dictionary comprehension:

d = {}
d["A"] = [[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 3242413, "NEW"], [1982, "PEAR", 1299021, "OLD"]]
d["B"] = [[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 1, "NEW"], [1982, "PEAR", 3242413, "OLD"]]

d = {k: [i for i in v if i[2] != 3242413] for (k, v) in d.items()}

Gives:

{'A': [[0, 'APPLE', 1202021, 'NEW'], [1982, 'PEAR', 1299021, 'OLD']], 'B': [[0, 'APPLE', 1202021, 'NEW'], [8, 'PEAR', 1, 'NEW']]}
  • Related