[Tutor] I can't believe this needs to be this complex

Kent Johnson kent37 at tds.net
Sat Aug 2 14:02:17 CEST 2008


On Sat, Aug 2, 2008 at 6:07 AM, Dick Moores <rdm at rcblue.com> wrote:
> I'm pretty new to Python's dictionaries, but I had a need for a function
> that would find the values in a dict that have more than one key each.

>From your sample output it appears that you want not just the values,
but a list of (value, keys) pairs for which there are more than one
key. It is easy to just build a reverse dict and filter its items:

In [15]: from collections import defaultdict
In [16]: rev=defaultdict(list)
In [18]: for k, v in d.iteritems():
    rev[v].append(k)

In [20]: [ [v, keys] for v, keys in rev.iteritems() if len(keys) > 1 ]

Out[20]:
[[1, ['a', 'e', 'g']],
 [2, ['b', 'f', 'i', 'h']],
 [4, ['d', 'j']],
 ['U.S. Senator', ['John McCain', 'Barack Obama']],
 [56, [45, 55]]]

This also has the advantage of making only two passes over the data so
its performance should be O(n). Your solution and Andre's make one or
more passes over the data for each data element so they will have
O(n*n) performance meaning for a large dict they could be very slow.

Kent


More information about the Tutor mailing list