dd90p
dd90p

Reputation: 513

how to combine the common key and join the values in the dictionary python

I have one list which contain a few dictionaries.

   [{u'TEXT242.txt': u'work'},{u'TEXT242.txt': u'go to work'},{u'TEXT1007.txt': u'report'},{u'TEXT797.txt': u'study'}]

how to combine the dictionary when it has the same key. for example: u'work', u'go to work'are under one key:'TEXT242.txt', so that i can remove the duplicated key.

 [{u'TEXT242.txt': [u'work', u'go to work']},{u'TEXT1007.txt': u'report'},{u'TEXT797.txt': u'study'}]

Upvotes: 0

Views: 95

Answers (2)

宏杰李
宏杰李

Reputation: 12158

from collections import defaultdict
before = [{u'TEXT242.txt': u'work'},{u'TEXT242.txt': u'go to work'},{u'TEXT1007.txt': u'report'},{u'TEXT797.txt': u'study'}]
after = defaultdict(list)
for i in before:
    for k, v in i.items():
        after[k].append(v)

out:

defaultdict(list,
            {'TEXT1007.txt': ['report'],
             'TEXT242.txt': ['work', 'go to work'],
             'TEXT797.txt': ['study']})

This technique is simpler and faster than an equivalent technique using dict.setdefault()

Upvotes: 2

kindall
kindall

Reputation: 184161

The setdefault method of dictionaries is handy here... it can create an empty list when a dictionary key doesn't exist, so that you can always append the value.

dictlist = [{u'TEXT242.txt': u'work'},{u'TEXT242.txt': u'go to work'},{u'TEXT1007.txt': u'report'},{u'TEXT797.txt': u'study'}]
newdict = {}

for d in dictlist:
    for k in d:
        newdict.setdefault(k, []).append(d[k])

Upvotes: 2

Related Questions