Jonathan Allen Grant
Jonathan Allen Grant

Reputation: 3658

How to Unique and Sort values from a list of dictionaries in python?

Suppose I have a list of dictionaries. Each dictionary has the same keys, but potentially different values per key. How do I get a list of unique values that are sorted alphabetically? Assume each value is a string.

Is there a better way than looping through each dictionary, adding each value to a list, sorting that list, and then removing non-unique values?

Upvotes: 1

Views: 215

Answers (1)

Elisha
Elisha

Reputation: 23780

I'm not sure how simple it can be, but using groupby and and set this can be shorter (python 2.x example):

from itertools import chain, groupby
from operator import itemgetter

dicts = [{'a': 's1'}, {'a': 's2'}, {'a': 's2', 'b': 's3'}]

union = {k: sorted(set(map(itemgetter(1), items))) for k, items in
         groupby(sorted(chain.from_iterable(d.iteritems() for d in dicts)),
                 key=itemgetter(0))}

# union = {'a': ['s1', 's2'], 'b': ['s3']}

Upvotes: 4

Related Questions