Volume069
Volume069

Reputation: 63

list of dictionary compare first value of first dict with first value of next dict

I have a list of dictionaries, for example:

l = [{"a":1, "b":2, "c":3}, {"a":1, "b":2, "c":4}, {"a":1, "b":7, "c":4}, {"a":2, "b":7, "c":4}] 

I need to create a nested dictionary if value of "a" are equal. I have tried:

l2 = [l[i] for i in range(len(l)-1) if l[i].get('a') == l[i+1].get('a')]
d = {"element"+ str(index): x for index, x in enumerate(l2, start=1)}

But in the output, I'm getting it skips one element:

{'element1': {'a': 1, 'b': 2, 'c': 3}, 'element2': {'a': 1, 'b': 2, 'c': 4}}

Expected output:

{'element1': {'a': 1, 'b': 2, 'c': 3}, 'element2': {'a': 1, 'b': 2, 'c': 4}, 'element3': {"a":1, "b":7, "c":4}}

Could someone please help me, what am I doing wrong?

Upvotes: 0

Views: 260

Answers (1)

Ido
Ido

Reputation: 168

Try this:

out = {f'element{i + 1}': j for i, j in enumerate(l) if any(j['a'] == k['a'] for k in l[:i] + l[i+1:])}

Output:

{'element1': {'a': 1, 'b': 2, 'c': 3}, 'element2': {'a': 1, 'b': 2, 'c': 4}, 'element3': {'a': 1, 'b': 7, 'c': 4}}

Upvotes: 1

Related Questions