Luiz Matias
Luiz Matias

Reputation: 49

Combining keys with values of a dictionary in python

A have a dictionary, such as the following.

dict1 = {
          'a':['b','c'],
          'd':['e','f']
        }

I want to combine the keys with the values (if the values are in the keys). So the output will looks like this:

dict1 = {
         'a':['b','c'],
         'b':['a','c'],
         'c':['a','b'],
         'd':['e','f'],
         'e':['d','f'],
         'f':['d','e']
        }

How can I do that in Python?

Upvotes: 1

Views: 68

Answers (2)

caot
caot

Reputation: 3318

The follows worked:

dict1 = {
          'a':['b','c'],
          'd':['e','f']
        }

dict2 = { }

for k, v in dict1.items():
    for x in v:
        v_copy = v[:]
        v_copy.remove(x)
        dict2.update({x: [k] + v_copy})


dict1.update(dict2)


print(dict1)

Upvotes: 2

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

You can build a set containing the key and values for each pair, and build the dictionary entries from that:

dict1 = {
          'a':['b','c'],
          'd':['e','f']
        }

sets = [set([key]) | set(values) for key, values in dict1.items() ]
# [{'a', 'b', 'c'}, {'f', 'd', 'e'}]

out = {}
for s in sets:
    for key in s:
        out[key] = list(s-set([key]))
print(out)

Output:

{'a': ['b', 'c'], 'b': ['a', 'c'], 'c': ['a', 'b'],
 'f': ['d', 'e'], 'd': ['f', 'e'], 'e': ['f', 'd']}

Upvotes: 2

Related Questions