Home > Mobile >  How to remove subset dictionaries from list of dictionaries
How to remove subset dictionaries from list of dictionaries

Time:01-10

I have a list of dictionaries, and some of them are subsets:

l = [
    {'zero': 'zero', 'one': 'example', 'two': 'second'}, 
    {'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
    {'zero': 'zero'},
    {'zero': 'non-zero', 'one': 'example'}, ...
]

And I want to create a new list of dictionaries that do not contain a subset of dictionaries.

res = [
    {'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
    {{'zero': 'non-zero', 'one': 'example'}, ...
]

CodePudding user response:

This work around will create a new list that only contains dictionaries that are not subsets of any other dictionary in the list

res = [
    d for d in l 
    if not any(set(d.items()).issubset(set(other.items()))
    for other in l if other != d)
    ]

print(res)

Output:

[{'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
 {'zero': 'non-zero', 'one': 'example'}]
  • Related