Jau L
Jau L

Reputation: 904

flatten list of dictionaries python

So I have the following list of lists, and I'm trying to reduce the size by merging duplicates only if the lists items match exactly. order is significant (changing items order will be an issue). also they are not equal-sized lists.

Example:

List = [["a", "b", "c", "d", "e"], ["a", "b"], ["a", "b", "c", "d", "e", "f"], ["a"], ["a", "b", "c", "d", "e"], ["a", "b"]]

I'm expecting the following output:

List = [["a", "b", "c", "d", "e"], ["a", "b"], ["a", "b", "c", "d", "e", "f"], ["a"]]

this is the code:

def consolidate(all_list):
    a = {}
    for v in all_list:
        if len(v) > 0:
            k = v[0]
            if k not in a: a[k] = []
                a[k].append(v[1:])
    for k in a:
        a[k] = consolidate(a[k])
    return a

However, it does not seem to work.

Upvotes: 0

Views: 37

Answers (1)

Sebastien D
Sebastien D

Reputation: 4482

Simply do :

output = []
for x in List:
    if x not in output : output.append(x)
output

Output

[['a', 'b', 'c', 'd', 'e'], ['a', 'b'], ['a', 'b', 'c', 'd', 'e', 'f'], ['a']]

Upvotes: 2

Related Questions