Converting a nested dictionary to a list

2024/11/14 22:21:46

I know there are many dict to list questions on here but I can't quite find the information I need for my situation so I'm asking a new quetion.

Some background: I'm using a hierarchical package for my models and the built-in function which generates the tree structure outputs a nested loop to indicate parents, children, etc. My goal is to keep the logic in views and output a list so that I can simply loop over it in my templates.

Here is my data, in the tree structure:

1
-1.1
--1.1.1
---1.1.1.1
--1.1.2
-1.2
--1.2.1
--1.2.2
-1.3

Here is the nested dictionary I am getting as a result

{<Part: 1.1>:{<Part: 1.1.1>:{<Part: 1.1.1.1>: {}}, <Part: 1.1.2>: {}},<Part: 1.2>: {<Part: 1.2.1>: {},<Part: 1.2.2>: {}}, <Part: 1.3>: {}
}

or if you don't like the way I tried to break it up, here is what I get in a single line:

{<Part: 1.1>: {<Part: 1.1.1>: {<Part: 1.1.1.1>: {}}, <Part: 1.1.2>: {}}, <Part: 1.2>: {<Part: 1.2.1>: {}, <Part: 1.2.2>: {}}, <Part: 1.3>: {}}

What I'd like is to get:

[<Part: 1.1>, <Part: 1.1.1>, <Part: 1.1.1.1>, <Part: 1.1.2>, <Part: 1.2>, <Part: 1.2.2>, <Part: 1.2.1>, <Part: 1.3>,]

I've tried just iterating over the key in dict.items but then I only get the top level keys (1.1, 1.2, 1.3)

What do I need to do to get deeper?

thanks!

Answer

I think recursion can be your friend :

top = {"<Part: 1.1>": {"<Part: 1.1.1>": {"<Part: 1.1.1.1>": {}}, "<Part: 1.1.2>": {}}, "<Part: 1.2>": {"<Part: 1.2.1>": {}, "<Part: 1.2.2>": {}}, "<Part: 1.3>": {}}def grab_children(father):local_list = []for key, value in father.iteritems():local_list.append(key)local_list.extend(grab_children(value))return local_listprint grab_children(top)
https://en.xdnf.cn/q/72282.html

Related Q&A

Pandas dataframe : Operation per batch of rows

I have a pandas DataFrame df for which I want to compute some statistics per batch of rows. For example, lets say that I have a batch_size = 200000. For each batch of batch_size rows I would like to ha…

Combining grid/pack Tkinter

I know there have been many questions on grid and pack in the past but I just dont understand how to combine the two as Im having difficulties expanding my table in both directions (row/column).Buttons…

Mocking assert_called_with in Python

Im having some trouble understanding why the following code does not pass:test.pyimport mock import unittestfrom foo import Fooclass TestFoo(unittest.TestCase):@mock.patch(foo.Bar)def test_foo_add(self…

Python select() behavior is strange

Im having some trouble understanding the behavior of select.select. Please consider the following Python program:def str_to_hex(s):def dig(n):if n > 9:return chr(65-10+n)else:return chr(48+n)r = wh…

Moving items up and down in a QListWidget?

In a QListWidget I have a set of entries. Now I want to allow the user to sort (reorder) these entries through two buttons (Up/Down).Heres part of my code:def __init__(self):QtGui.QMainWindow.__init__(…

How to resize a tiff image with multiple channels?

I have a tiff image of size 21 X 513 X 513 where (513, 513) is the height and width of the image containing 21 channels. How can I resize this image to 21 X 500 X 375?I am trying to use PILLOW to do …

Losing elements in python code while creating a dictionary from a list?

I have some headache with this python code.print "length:", len(pub) # length: 420pub_dict = dict((p.key, p) for p in pub)print "dict:", len(pub_dict) # length: 163If I understand t…

How to set Font size or Label size to fit all device

How to set kivy font size or label size so that it will fit all phone-device screen? (fit by means does not overlap with the boundary, rectangle, or even the screen)I know the Buttons and some other W…

Using tweepy to access Twitters Streaming API

Im currently having trouble getting example code for using tweepy to access Twitters Streaming API to run correctly (err...or at least how I expect it to run). Im using a recent clone of tweepy from Gi…

Jupyter notebook, how to run multiple cells simultaneously?

I defined a python function which run a bash script. Lets say the function is: calc(x,y,z). If I run this function in python with some variables,>>> calc(1,2,3)It generates a C code which simu…