How to remove 'D' from the lists wherever it exists in this python dict:…
- User
How to remove 'D' from the lists wherever it exists in this python dict: {'A':['Material', 'Supplier', ], 'B':['Material', 'Supplier', 'Country_code', 'D' ], 'fixed_feat':['Material', 'Plan', 'D']}
- Assistant
You can remove 'D' from the lists by iterating over the values of the dictionary and filtering out the 'D' element wherever it appears:
coded = {'A':['Material', 'Supplier', ], 'B':['Material', 'Supplier', 'Country_code', 'D' ], 'fixed_feat':['Material', 'Plan', 'D']} for key, value in d.items(): d[key] = list(filter(lambda x: x != 'D', value)) print(d)Output:
code{'A': ['Material', 'Supplier'], 'B': ['Material', 'Supplier', 'Country_code'], 'fixed_feat': ['Material', 'Plan']} - User
give one-liner
- Assistant
Here's the one-liner:
coded = {k: [i for i in v if i != 'D'] for k, v in d.items()}This uses a dictionary comprehension with a list comprehension inside to filter out the 'D' element from the lists of each key-value pair in the dictionary.
- User
Modify it to account only the keys which have lists as their value.
- Assistant
Here's the modified one-liner that only performs the modification on keys that have lists as their values:
coded = {k: [i for i in v if i != 'D'] if isinstance(v, list) else v for k, v in d.items()}This uses an
isinstance()check to only perform the list comprehension and filtering on keys whose values are of typelist. If the value is not a list, it is left unchanged.