How can I make it with this structure?

Question:

#li = [1,1,2,2,4,4,4,7,5,5]

#dict_index = [1,2,3,4,5,6,7,8,9,10]

to make this▽
make_dict = {1:[2],2:[3,4],3:[x],4:[5,6,7],5:[9,10],6:[x],7:[8],8:[x],9:[x],10:[x]}


I want to make a "make_dict" like the one below by referring to "li" and "dict_index"…
It seems like a tree of data structures.
How can I solve this..?


make_dict(Tree)

Asked By: 김민수

||

Answers:

You could simply loop through the two lists and check each number in the dict_index list with each number of li to find what indices match. In my code, I have followed your example of having the first spot of a list being 1, but depending on your use case, it might be better to have it start at 0. To do this just remove the +1 in the index_list.append(j+1). Here is the function I wrote:


li = [1,1,2,2,4,4,4,7,5,5]


dict_index = [1,2,3,4,5,6,7,8,9,10]


def make_dict(li,dict_index):
    
    #make empty dictionary to store indices in    
    our_dict = {}
    
    #loop through all numbers of the dict_index
    for i in range(len(dict_index)):
        
        current_number = dict_index[i]
        
        #create empty index_list
        index_list = []
        
        #loop through list li to check what indices match our current number
        for j in range(len(li)):
            
            #If we have a match, we add the index to our index list
            if li[j] == current_number:
                index_list.append(j+1)
        
        #when we are done looping through li we add result to our dictionary
        if index_list: 
            #if not empty, we add our index list
            our_dict[current_number] = index_list 
        else:
            #otherwise, if we had no match, we just add None to the dictionary
            our_dict[current_number] = None
    
    #return our dictionary at the end
    return our_dict

index_dict = make_dict(li,dict_index)


This will yield the following output for index_dict:

{1: [1, 2], 2: [3, 4], 3: None, 4: [5, 6, 7], 5: [9, 10], 6: None,
 7: [8], 8: None, 9: None, 10: None}
Answered By: thestarwarsnerd

You can zip li and dict_index, iterate through the parent-child pairs, and append child to the sub-list under the parent key. Initialize non-existing keys with the dict.setdefault method:

tree = {}
for parent, child in zip(li, dict_index):
    if parent != child:
        tree.setdefault(parent, []).append(child)
    tree.setdefault(child, [])

so that given the sample input, tree would become:

{1: [2], 2: [3, 4], 3: [], 4: [5, 6, 7], 5: [9, 10], 6: [], 7: [8], 8: [], 9: [], 10: []}

Demo: https://replit.com/@blhsing/LikablePoshBundledsoftware

Answered By: blhsing
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.