Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove a list from dictionary value lists using filter() in Python3

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# 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"]]

>Solution :

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']]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading