Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all Key-Elements by the same Value in Dicts

I have question about Dictionaries in Python.

here it is:

I have a dict like dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }

Now i want to get all Key-Elements by the same value and save it in a new dict.

The new Dict should be look like:

new_dict = { 'b':('cdf'), 'a':('abc','gh'), 'g':('fh','hfz')}

like image 846
Sv3n Avatar asked Feb 04 '11 16:02

Sv3n


2 Answers

Here's a naive implementation. Someone with better Python skills can probably make it more concise and awesome.

dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }

new_dict = {}
for pair in dict.items():
    if pair[1] not in new_dict.keys():
        new_dict[pair[1]] = []

    new_dict[pair[1]].append(pair[0])

print new_dict

This produces

{'a': ['abc', 'gh'], 'b': ['cdf'], 'g': ['fh', 'hfz']}
like image 127
Adam Lear Avatar answered Oct 07 '22 09:10

Adam Lear


If you are fine with lists instead of tuples in the new dictionary, you can use

from collections import defaultdict
some_dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }
new_dict = defaultdict(list)
for k, v in some_dict.iteritems():
    new_dict[v].append(k)

If you want to avoid the use of defaultdict, you could also do

new_dict = {}
for k, v in some_dict.iteritems():
    new_dict.setdefault(v, []).append(k)
like image 35
Sven Marnach Avatar answered Oct 07 '22 10:10

Sven Marnach