Ogen
Ogen

Reputation: 6709

Create python dictionary from value of another dictionary?

I am trying to efficiently construct a python dictionary from the keys' values of another dictionary.

For example...

    dict1 = {'foo': [1, 3, 7], 'bar': [2, 4, 8]} ## note: all values in {key: value} will be unique
    ## Algorithm here...
    dict2 = {1: [3, 7], 3: [1, 7], 7: [1, 3], 2: [4, 8], 4: [2, 8], 8: [2, 4]}

I can get this result through brute force methods but these dictionaries are for graphs with over 100000 nodes so I need this to be efficient.

Any help would be greatly appreciated.

Upvotes: 0

Views: 103

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208465

Here is how I would do this:

dict2 = {k: x[:i] + x[i+1:] for x in dict1.values() for i, k in enumerate(x)}

If you are on Python 2.x you may want to use dict1.itervalues().

Upvotes: 6

Related Questions