1

I have a list of dictionaries in Python:

[{u'value': u'firstname', u'key': u'Coach'}, 
 {u'value': u'lastname', u'key': u'Coach'}, 
 {u'value': u'age', u'key': u'Coach'}, 
 {u'value': u'firstname', u'key': u'Player'}, 
 {u'value': u'league', u'key': u'Player'}]

How can I remove duplicate key from a list of dictionaries and merge their values into a list as shown below:

l = [('Coach', ['firstname', 'lastname', 'age']), 
     ('Player', ['firstname', 'league'])]

Iterate over list items

for k, v in l:
    print k, v

2 Answers 2

4

You could use defaultdict with list as value type in order to collect values:

In [5]: from collections import defaultdict

In [6]: data = [{u'value': u'firstname', u'key': u'Coach'}, 
 {u'value': u'lastname', u'key': u'Coach'}, 
 {u'value': u'age', u'key': u'Coach'}, 
 {u'value': u'firstname', u'key': u'Player'}, 
 {u'value': u'league', u'key': u'Player'}]

In [7]: l = defaultdict(list)

In [8]: for row in data:
   ...:     l[row['key']].append(row['value'])
   ...:     

In [9]: l
Out[9]: 
defaultdict(list,
            {'Coach': ['firstname', 'lastname', 'age'],
             'Player': ['firstname', 'league']})

And then you could easily convert the dictionary into a list of tuples using items method:

In [10]: list(l.items())
Out[10]: 
[('Coach', ['firstname', 'lastname', 'age']),
 ('Player', ['firstname', 'league'])]
Sign up to request clarification or add additional context in comments.

Comments

3
[(k, [x['value'] for x in v]) for k, v in itertools.groupby(sorted(data, key=lambda x: x['key']), lambda d: d['key'])]

groupby is in the standard module itertools.

EDIT: Thank @soon for pointing out that itertools.groupby requires input sequence being consecutive, thus need to sort beforehand.

2 Comments

groupby groups consecutive elements only
operator.itemgetter could also be useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.