How to flatten a nested dictionary? [duplicate]

2024/7/7 4:36:24

Is there a native function to flatten a nested dictionary to an output dictionary where keys and values are in this format:

_dict2 = {'this.is.an.example': 2,'this.is.another.value': 4,'this.example.too': 3,'example': 'fish'
}

Assuming the dictionary will have several different value types, how should I go about iterating the dictionary?

Answer

You want to traverse the dictionary, building the current key and accumulating the flat dictionary. For example:

def flatten(current, key, result):if isinstance(current, dict):for k in current:new_key = "{0}.{1}".format(key, k) if len(key) > 0 else kflatten(current[k], new_key, result)else:result[key] = currentreturn resultresult = flatten(my_dict, '', {})

Using it:

print(flatten(_dict1, '', {})){'this.example.too': 3, 'example': 'fish', 'this.is.another.value': 4, 'this.is.an.example': 2}
https://en.xdnf.cn/q/120428.html

Related Q&A

Find an element in a list of tuples in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…

print dictionary values which are inside a list in python

I am trying to print out just the dict values inside a list in python.car_object = {}cursor = self._db.execute(SELECT IDENT, MAKE, MODEL, DISPLACEMENT, POWER, LUXURY FROM CARS)for row in cursor:objectn…

Triangle of numbers on Python

Im asked to write a loop system that prints the following:0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0However, my script prints this:0 1…

Using regex to ignore invalid syntax [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

What is the requirements.txt file? What should be in it in this particular case?

I am switching from Replit to PebbleHost to host my Python bot. What do I put in my requirements.txt file? These are the imports that I have at the start of my bot. import asyncio import datetime impo…

Is this a linux or a virtualenv error?

I asked this question 4 days ago.Now, when I open a terminal, I see this:and this:Is it related to the initial problem i had, or it a python and virtualenv issue?

Python code to authenticate to website, navigate through links and download files

Im looking something which could be interesting to you as well. Im developing a feature using Python, which should be able to authenticate (using userid/password and/or with other preferred authentica…

How to get sum of products of all combinations in an array in Python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

How to get value from entry (Tkinter), use it in formula and print the result it in label

When using the function entry of Tkinter, you can write a string value and do things with it; but Im actually working with formulas. The idea is fairly simple: to put a bunch of boxes to fill with numb…

Printing tuples in a list

Im not getting how to proceed with this problem in lists,can any one help me out? Thanks in advance.input is :l = [(1,2),(3,4),(5,6)]output is:[(1,3,5),(2,4,6)]