To build a multiple-level dictionary within a for loop without using the defaultdict function, you can follow the below steps:
Create an empty dictionary.
Loop through the data and split it into different levels using keys.
Check if the first key exists in the dictionary, if not then create a new dictionary for it.
Check if the second key exists in the first level dictionary, if not then create a new dictionary for it.
Repeat the process for all the levels of the dictionary.
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'
}
}
}
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
Asked: 2023-06-24 05:21:52 +0000
Seen: 12 times
Last updated: Jun 24 '23
How can I print all but the first 1000 Lines from a File in Bash?
Why does my method execute only once within a while loop?
What is the method for bypassing the entire current loop if an error occurs?
How can an array of objects be initialized in C# without implementing a loop?
How can resetting a list be avoided during a loop?
What is causing fs.readFileSync() to restrict the number of simultaneous tasks in node.js?
How can a DropDownListFor be generated in a loop?
How can the legend of a Seaborn scatterplot be updated within a loop?
What are the ways to prevent an infinite loop while using setState()?
What is the way to implement the Worksheets.Cells format within a for loop?