1

I am trying build a complete path for keys in a dictionary.

The dictionary is built where the keys are all unique but the values are not.

mydict = {'12345': '11', '45678': '11', '11': '2', '2': '6', '6': '6', '789': '2'}

what i am trying to do is get the full path of each key until the key == value where the output would be a file that looks like this:

12345, 11, 2, 6

45678, 11, 2, 6

11, 2, 6

2, 6

6

789, 2, 6

I can search the dictionary once to get the first value but I don't know how to use that value as the next key search and keep all the associations correct. The dictionary is only integers and the keys are in numerical order.

4

1 に答える 1

2

これはそれを行う必要があります:

In [53]: mydict = {'12345': '11', '45678': '11', '11': '2', '2': '6', '6': '6', '789': '2'}

In [54]: answer = []

In [55]: for key in mydict:
   ....:     path = [key]
   ....:     while mydict[key] != key:
   ....:         key = mydict[key]
   ....:         path.append(key)
   ....:     answer.append(path)
   ....:     

In [56]: answer
Out[56]: 
[['11', '2', '6'],
 ['789', '2', '6'],
 ['45678', '11', '2', '6'],
 ['2', '6'],
 ['6'],
 ['12345', '11', '2', '6']]
于 2013-02-26T07:51:42.697 に答える