Ask Your Question
4

What is the procedure for building a multiple-level dictionary within a for loop without utilizing the defaultdict function?

asked 2023-06-24 05:21:52 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-24 05:41:01 +0000

ladyg gravatar image

To build a multiple-level dictionary within a for loop without using the defaultdict function, you can follow the below steps:

  1. Create an empty dictionary.

  2. Loop through the data and split it into different levels using keys.

  3. Check if the first key exists in the dictionary, if not then create a new dictionary for it.

  4. Check if the second key exists in the first level dictionary, if not then create a new dictionary for it.

  5. Repeat the process for all the levels of the dictionary.

  6. Finally, add the value to the last level.

Here is an example code:

data = [('a', 'b', 'c', 'value1'), ('d', 'e', 'f', 'value2')]

result_dict = {}

for item in data:
    level1, level2, level3, value = item[0], item[1], item[2], item[3]
    if level1 not in result_dict:
        result_dict[level1] = {}
    if level2 not in result_dict[level1]:
        result_dict[level1][level2] = {}
    if level3 not in result_dict[level1][level2]:
        result_dict[level1][level2][level3] = value

print(result_dict)

Output:

{
    'a': {
        'b': {
            'c': 'value1'
        }
    },
    'd': {
        'e': {
            'f': 'value2'
        }
    }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-24 05:21:52 +0000

Seen: 12 times

Last updated: Jun 24 '23