0

I have the following dictionary:

terms = {"Taste Term":{'children': ['Receptor', 'Descriptor', 'Modulator', 'Tissue'], 'parent': []},"Receptor":{'children': ['ion channel'], 'parent': ['Taste Term']}, "Descriptor":{'children': [], 'parent': ['Taste Term']}, "Modulator":{'children': [], 'parent': ['Taste Term']},"Tissue":{'children': [], 'parent': ['Taste Term']}}

when I dump this dictionary with print json.dumps(terms, indent=4) i get the following Json file:

{
"Descriptor": {
 "children": [], 
 "parent": [
 "Taste Term"
 ]
}, 
"Tissue": {
 "children": [], 
 "parent": [
 "Taste Term"
 ]
}, 
"Receptor": {
 "children": [
 "ion channel"
 ], 
 "parent": [
 "Taste Term"
 ]
}, 
"Modulator": {
 "children": [], 
 "parent": [
 "Taste Term"
 ]
}, 
"Taste Term": {
 "children": [
 "Receptor", 
 "Descriptor", 
 "Modulator", 
 "Tissue"
 ], 
 "parent": []
}
}

the json file i want looks like this:

{
"name":"Taste Term",
"children": [
 {
 "name":"Receptor",
 "children": [
 {"name":"ion channel"}
 ]
 },
 {"name":"Descriptor"},
 {"name":"Modulator"},
 {"name":"Tissue"}
 ]
 }

Now, How can I edit my dictionary to get to the correct structure for Json to output the lower Json file? So I need to edit the dictionary terms in such a way that the children have the children in them.

martineau
124k29 gold badges181 silver badges319 bronze badges
asked Apr 30, 2015 at 7:50
9
  • 5
    First worry about how to transform the dict into the other dict. The "converting to JSON" part is trivial, and not really relevant to the problem. Commented Apr 30, 2015 at 7:52
  • Hi, you recommend transforming this dictionary to another dictionary with a different layout? A layout that can be directly dumped? Commented Apr 30, 2015 at 7:56
  • 1
    @Henkes: yes. The json library produces valid JSON as a one-on-one translation of the Python dictionary, list and value structure. You need to do the transformation first. Commented Apr 30, 2015 at 7:57
  • 2
    What do you already tried ? I clearly see what you have, what you try to get, but I can't figure what you already tried to help you to do it better... Commented Apr 30, 2015 at 8:05
  • edited my question, The children's children is what I'm struggeling with. (and their children etc.) Commented Apr 30, 2015 at 8:32

1 Answer 1

1

Often the simplest way to deal with recursive data structures is by using a recursive function. In this case it's possible to write one that transforms the "nodes" in the flat dictionary you have into the kind needed for the nested dictionary structure you want. Once this is done you can just json.dumps() the result to get it into JSON format.

In the code below I've corrected the syntax of the starting terms dictionary provided in your question and reformatted it to clearly show its structure.

import json
terms = {
 'root': {'p': [], 'c': ['branch1', 'branch2', 'branch3']},
 'branch1': {'p': ['root'], 'c': ['branch1.1']},
 'branch2': {'p': ['root'], 'c': []},
 'branch3': {'p': ['root'], 'c': []},
 'branch1.1': {'p': ['branch1'], 'c': []}
}
def transform(d, parent):
 return (
 {'name': parent}
 if not d[parent]['c'] else
 {'name': parent,
 'children': [transform(d, child) for child in d[parent]['c']]}
 )
print(json.dumps(transform(terms, 'root'), indent=2))

Output:

{
 "name": "root",
 "children": [
 {
 "name": "branch1",
 "children": [
 {
 "name": "branch1.1"
 }
 ]
 },
 {
 "name": "branch2"
 },
 {
 "name": "branch3"
 }
 ]
}
answered Apr 30, 2015 at 11:21
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks the recursive transform function is exactly what I needed! With regular for loops it didn't work.
@HR123r: One very flexible way is by something called "autovivification". More generally, look up things related to building the data-structure known as a "Tree". They can also be represented as nested sequences.
Although there's only one dictionary here, it contains the nodes of the whole Tree, which are represented with id strings here — so it's equivalent to a dictionary of dictionaries. That means it should be possible to convert one into the other. Therefor, I think, that you can think about and do things with whichever representation is the most convenient for you (and convert it the other as needed). If I run across and good example or reference like you want, I'll let you know.
Yes — I misspoke. It's a dict of dicts, but the physical nesting never goes any deeper (so it'll never become a dict of dicts of dicts of ...etc) but logically it can represent that.
@HR123r: Don't think that's a good idea since it has little to do with this question. Suggest you try taking the output produced here and reverse-transforming it back into the original structure. Then, if you can't figure that out, post a separate question here on SO describing what you want to do and showing your attempt.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.