Python. Manipulation with a list of dictionaries

dictionary, list, python

Solution

The first [well, second, with some edits..] thing that comes to mind is this:

def get_superdicts(dictlist):
    superdicts = []
    for d in sorted(dictlist, key=len, reverse=True):
        fd = set(d.items())
        if not any(fd <= k for k in superdicts):
            superdicts.append(fd)
    new_dlist = map(dict, superdicts)
    return new_dlist

which gives:

>>> a = [{'apples': 'green', 'oranges': 'big'}, {'apples': 'green', 'oranges': 'big', 'bananas': 'fresh'}, {'apples': 'red', 'oranges': 'big'}, {'apples': 'green', 'oranges': 'big', 'bananas': 'rotten'}]
>>> 
>>> get_superdicts(a)
[{'apples': 'red', 'oranges': 'big'}, 
 {'apples': 'green', 'oranges': 'big', 'bananas': 'rotten'}, 
 {'bananas': 'fresh', 'oranges': 'big', 'apples': 'green'}]

[Originally I was using a `frozenset` here, thinking I could do some kind of clever set operation but obviously didn't come up with anything.]

Problem

Friends, I have a list of dictionaries: ``` my_list = [ {'oranges':'big','apples':'green'}, {'oranges':'big','apples':'green','bananas':'fresh'}, {'oranges':'big','apples':'red'}, {'oranges':'big','apples':'green','bananas':'rotten'} ] ``` I want to create a new list where partial duplicates are eliminated. In my case this dictionary must be eliminated: ``` {'oranges':'big','apples':'green'} ``` , because it duplicates longer dictionaries: ``` {'oranges':'big','apples':'green','bananas':'fresh'} {'oranges':'big','apples':'green','bananas':'rotten'} ``` Hence, the desired result: ``` [ {'oranges':'big','apples':'green','bananas':'fresh'}, {'oranges':'big','apples':'red'}, {'oranges':'big','apples':'green','bananas':'rotten'} ] ``` How to do it? Thanks a million!

Original source