-1

I am trying to work on this problem which basically takes a dictionary, table_one, with lists as it's values and i am trying to convert it into another dictionary, table_two, where the keys are values from table_one, however the values must match with the keys from table_one

Basically i want to convert this:

table_one = {'e0': ['v0', 'v1', 'v5'], 'e1': ['v1', 'v3', 'v4', 'v5'], 'e2':['v0', 'v2', 'v5']}

into this

table_two = {'v0' : ['e0', 'e2'], 'v1' : ['e0', 'e2'], 'v3':['e1'], 'v4' : ['e1'], 'v5' : ['e0', 'e1', 'e2'] 

So far i have come up with this code:

table_one = {'e0': ['v0', 'v1', 'v5'], 'e1': ['v1', 'v3', 'v4', 'v5'],
'e2':['v0', 'v2', 'v5']}
table_two = {}

for lists in table_one.values():
    for elements in lists: #iterates through values in each list
        if elements in table_one: #checks whether element belongs to key
             table_two[elements].append(table_one.keys())



print "Elements = ", table_two.items()'

I run into a logical error, with absolutely no output. Any suggestions?

mali30
  • 57
  • 1
  • 2
  • 7
  • you are searching for table_one values in table_one keys. It is the mistake. In the if statement, you need to search it with table_two keys. – Mithilesh_Kunal Feb 01 '19 at 05:36

1 Answers1

0

You can use defaultdict for this. And if you want the output to be normal dict, just change it after.

In [1]: from collections import defaultdict

In [2]: table_one = {'e0': ['v0', 'v1', 'v5'], 'e1': ['v1', 'v3', 'v4', 'v5'], 'e2':['v0', 'v2', 'v5']}

In [3]: table_two = defaultdict(list)

In [4]: for key, values in table_one.items():
   ...:     for v in values:
   ...:         table_two[v] += [key]
   ...:
   ...:

In [5]: table_two
Out[5]:
defaultdict(list,
        {'v0': ['e0', 'e2'],
         'v1': ['e0', 'e1'],
         'v5': ['e0', 'e1', 'e2'],
         'v3': ['e1'],
         'v4': ['e1'],
         'v2': ['e2']})

In [6]: table_two = dict(table_two)

In [7]: table_two
Out[7]:
{'v0': ['e0', 'e2'],
 'v1': ['e0', 'e1'],
 'v5': ['e0', 'e1', 'e2'],
 'v3': ['e1'],
 'v4': ['e1'],
 'v2': ['e2']}
Osman Mamun
  • 2,864
  • 1
  • 16
  • 22