Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging Key-Value Pairings in Dictionary

Tags:

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?

like image 274
user415663 Avatar asked Feb 25 '16 06:02

user415663


People also ask

How can you add the key-value pairs from one dictionary into another dictionary?

In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.

How do you merge key values in Python?

Method #1 : Using zip() + loop + defaultdict() The combination of above method can be used to perform this particular task. In this, we use zip function to match the like elements of lists with each other and loop is then used to assign the keys with value from zipped list to add value to a defaultdict.

How do you store key-value pairs in the dictionary?

The data in a dictionary is stored as a key/value pair. It is separated by a colon(:), and the key/value pair is separated by comma(,). The keys in a dictionary are unique and can be a string, integer, tuple, etc. The values can be a list or list within a list, numbers, string, etc.


2 Answers

>>> 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']}
like image 139
John La Rooy Avatar answered Oct 12 '22 18:10

John La Rooy


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"

like image 40
ZdaR Avatar answered Oct 12 '22 19:10

ZdaR