Python: How to group unsorted list of dictionary into new list
Question: I have a list like this:

    
    
    table=[{'device': 'a', 'iface': 'i1'}, {'device': 'a', 'iface': 'i2'}, {'device': 'a', 'iface': 'i4'}, {'device': 'b', 'iface': 'i5'}, {'device': 'a', 'iface': 'i3'}, {'device': 'b', 'iface': 'i7'}]
    

I want to group that list into a new list like this:

    
    
    newtable=[{'device':'a','iface':['i1','i2','i4','i3']},{'device':'b','iface':['i5','i7']}]
    

I have tried to use defaultdict from collections module but the result is not
what I expected. Please help me. Thanks in advance

> here what i have done:
    
    
    from collections import defaultdict
    table=[{'device': 'a', 'iface': 'i1'}, {'device': 'a', 'iface': 'i2'}, {'device': 'a', 'iface': 'i4'}, {'device': 'b', 'iface': 'i5'}, {'device': 'a', 'iface': 'i3'}, {'device': 'b', 'iface': 'i7'}]
    newtable=defaultdict(list)
    for row in table:
        newtable[row['device']].append(row['iface'])
    newtable=list(newtable)
    

and I lost from here. So sorry for my English.


Answer: Here is one way to do it - Just using `defaultdict` might not be enough. You
might have to process it a little further (just make sure you use better
variable names :) ):

    
    
    >>> from collections import defaultdict
    >>> xx = defaultdict(list)
    >>> table=[{'device': 'a', 'iface': 'i1'}, {'device': 'a', 'iface': 'i2'}, {'device': 'a', 'iface': 'i4'}, {'device': 'b', 'iface': 'i5'}, {'device': 'a', 'iface': 'i3'}, {'device': 'b', 'iface': 'i7'}]
    >>> for tab in table:
    ...   xx[tab['device']].append(tab['iface'])
    ... 
    >>> xx
    defaultdict(<type 'list'>, {'a': ['i1', 'i2', 'i4', 'i3'], 'b': ['i5', 'i7']})
    >>> yy = dict(xx)
    >>> yy
    {'a': ['i1', 'i2', 'i4', 'i3'], 'b': ['i5', 'i7']}
    
    >>> new_table = []
    >>> for a in yy:
    ...   new_table.append({'device': a, 'iface': yy[a]})
    ... 
    >>> new_table
    [{'device': 'a', 'iface': ['i1', 'i2', 'i4', 'i3']}, {'device': 'b', 'iface': ['i5', 'i7']}]
    

