20

I have a dictionary that consists of employee-manager as key-value pairs:

{'a': 'b', 'b': 'd', 'c': 'd', 'd': 'f'}

I want to show the relations between employee-manager at all levels (employee's boss, his boss's boss, his boss's boss's boss etc.) using a dictionary. The desired output is:

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

Here is my attempt which only shows the first level:

for key, value in data.items():
    if (value in data.keys()):
        data[key] = [value]
        data[key].append(data[value])

I can do another conditional statement to add the next level but this would be the wrong way to go about it. I'm not very familiar with dictionaries so what would be a better approach?

Eric
  • 2,636
  • 21
  • 25
user415663
  • 735
  • 2
  • 7
  • 9

3 Answers3

11
>>> D = {'a': 'b', 'b': 'd', 'c': 'd', 'd': 'f'}
>>> res = {}
>>> for k in D:
...     res[k] = [j] = [D[k]]
...     while j in D:
...         j = D[j]
...         res[k].append(j)
... 
>>> res
{'b': ['d', 'f'], 'c': ['d', 'f'], 'd': ['f'], 'a': ['b', 'd', 'f']}
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
7

You may use the concept of recursion as :

def get_linked_list(element, hierarchy, lst):
    if element:
        lst.append(element)
        return get_linked_list(hierarchy.get(element, ""), hierarchy, lst)
    else:
        return lst

And then access the hierarchy as:

>>> d = {'a': 'b', 'b': 'd', 'c': 'd', 'd': 'f'}   
>>> print {elem:get_linked_list(elem, d, [])[1:] for elem in d.keys()}
>>> {'a': ['b', 'd', 'f'], 'c': ['d', 'f'], 'b': ['d', 'f'], 'd': ['f']}

However care must be taken as this may get to an infinite loop if we have an item in the dictionary as "a": "a"

ZdaR
  • 22,343
  • 7
  • 66
  • 87
1
x={'a': 'b', 'b': 'd', 'c': 'd', 'd': 'f'}
d={}
l=x.keys()
for i in l:
    d.setdefault(i,[])
    d[i].append(x[i])
    for j in l[l.index(i)+1:]:
        if j==d[i][-1]:
            d[i].append(x[j])

print d

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

vks
  • 67,027
  • 10
  • 91
  • 124