Create a nested tree from list











up vote
0
down vote

favorite












From a list of lists, I would like to create a nested dictionary of which the keys would point to the next value in the sublist. In addition, I would like to count the number of times a sequence of sublist values occurred.



Example:



From a list of lists as such:



[['a', 'b', 'c'],
['a', 'c'],
['b']]


I would like to create a nested dictionary as such:



{
'a': {
{'b':
{
'c':{}
'count_a_b_c': 1
}
'count_a_b*': 1
},
{'c': {},
'count_a_c': 1
}
'count_a*': 2
},
{
'b':{},
'count_b':1
}
}


Please note that the names of the keys for counts do not matter, they were named as such for illustration.










share|improve this question




















  • 1




    Have you made any attempts to accomplish this that you are able to share?
    – rs311
    Nov 17 at 10:54










  • Unfortunately, none of my attempts were fruitful. I did spend several hours on the problem. The main problem is how to automate the nested structure with a for loop...
    – micoco
    Nov 17 at 11:01















up vote
0
down vote

favorite












From a list of lists, I would like to create a nested dictionary of which the keys would point to the next value in the sublist. In addition, I would like to count the number of times a sequence of sublist values occurred.



Example:



From a list of lists as such:



[['a', 'b', 'c'],
['a', 'c'],
['b']]


I would like to create a nested dictionary as such:



{
'a': {
{'b':
{
'c':{}
'count_a_b_c': 1
}
'count_a_b*': 1
},
{'c': {},
'count_a_c': 1
}
'count_a*': 2
},
{
'b':{},
'count_b':1
}
}


Please note that the names of the keys for counts do not matter, they were named as such for illustration.










share|improve this question




















  • 1




    Have you made any attempts to accomplish this that you are able to share?
    – rs311
    Nov 17 at 10:54










  • Unfortunately, none of my attempts were fruitful. I did spend several hours on the problem. The main problem is how to automate the nested structure with a for loop...
    – micoco
    Nov 17 at 11:01













up vote
0
down vote

favorite









up vote
0
down vote

favorite











From a list of lists, I would like to create a nested dictionary of which the keys would point to the next value in the sublist. In addition, I would like to count the number of times a sequence of sublist values occurred.



Example:



From a list of lists as such:



[['a', 'b', 'c'],
['a', 'c'],
['b']]


I would like to create a nested dictionary as such:



{
'a': {
{'b':
{
'c':{}
'count_a_b_c': 1
}
'count_a_b*': 1
},
{'c': {},
'count_a_c': 1
}
'count_a*': 2
},
{
'b':{},
'count_b':1
}
}


Please note that the names of the keys for counts do not matter, they were named as such for illustration.










share|improve this question















From a list of lists, I would like to create a nested dictionary of which the keys would point to the next value in the sublist. In addition, I would like to count the number of times a sequence of sublist values occurred.



Example:



From a list of lists as such:



[['a', 'b', 'c'],
['a', 'c'],
['b']]


I would like to create a nested dictionary as such:



{
'a': {
{'b':
{
'c':{}
'count_a_b_c': 1
}
'count_a_b*': 1
},
{'c': {},
'count_a_c': 1
}
'count_a*': 2
},
{
'b':{},
'count_b':1
}
}


Please note that the names of the keys for counts do not matter, they were named as such for illustration.







python dictionary tree






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 17 at 13:26

























asked Nov 17 at 10:46









micoco

6410




6410








  • 1




    Have you made any attempts to accomplish this that you are able to share?
    – rs311
    Nov 17 at 10:54










  • Unfortunately, none of my attempts were fruitful. I did spend several hours on the problem. The main problem is how to automate the nested structure with a for loop...
    – micoco
    Nov 17 at 11:01














  • 1




    Have you made any attempts to accomplish this that you are able to share?
    – rs311
    Nov 17 at 10:54










  • Unfortunately, none of my attempts were fruitful. I did spend several hours on the problem. The main problem is how to automate the nested structure with a for loop...
    – micoco
    Nov 17 at 11:01








1




1




Have you made any attempts to accomplish this that you are able to share?
– rs311
Nov 17 at 10:54




Have you made any attempts to accomplish this that you are able to share?
– rs311
Nov 17 at 10:54












Unfortunately, none of my attempts were fruitful. I did spend several hours on the problem. The main problem is how to automate the nested structure with a for loop...
– micoco
Nov 17 at 11:01




Unfortunately, none of my attempts were fruitful. I did spend several hours on the problem. The main problem is how to automate the nested structure with a for loop...
– micoco
Nov 17 at 11:01












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










i was curious how i would do this and came up with this:



lst = [['a', 'b', 'c'],
['a', 'c'],
['b']]

tree = {}
for branch in lst:
count_str = 'count_*'
last_node = branch[-1]
cur_tree = tree
for node in branch:
if node == last_node:
count_str = count_str[:-2] + f'_{node}'
else:
count_str = count_str[:-2] + f'_{node}_*'
cur_tree[count_str] = cur_tree.get(count_str, 0) + 1
cur_tree = cur_tree.setdefault(node, {})


nothing special happening here...



for your example:



import json
print(json.dumps(tree, sort_keys=True, indent=4))


produces:



{
"a": {
"b": {
"c": {},
"count_a_b_c": 1
},
"c": {},
"count_a_b_*": 1,
"count_a_c": 1
},
"b": {},
"count_a_*": 2,
"count_b": 1
}


it does not exactly reproduce what you imagine - but that is in part due to the fact that your desired result is not a valid python dictionary...



but it may be a starting point for you to solve your problem.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53350458%2fcreate-a-nested-tree-from-list%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    i was curious how i would do this and came up with this:



    lst = [['a', 'b', 'c'],
    ['a', 'c'],
    ['b']]

    tree = {}
    for branch in lst:
    count_str = 'count_*'
    last_node = branch[-1]
    cur_tree = tree
    for node in branch:
    if node == last_node:
    count_str = count_str[:-2] + f'_{node}'
    else:
    count_str = count_str[:-2] + f'_{node}_*'
    cur_tree[count_str] = cur_tree.get(count_str, 0) + 1
    cur_tree = cur_tree.setdefault(node, {})


    nothing special happening here...



    for your example:



    import json
    print(json.dumps(tree, sort_keys=True, indent=4))


    produces:



    {
    "a": {
    "b": {
    "c": {},
    "count_a_b_c": 1
    },
    "c": {},
    "count_a_b_*": 1,
    "count_a_c": 1
    },
    "b": {},
    "count_a_*": 2,
    "count_b": 1
    }


    it does not exactly reproduce what you imagine - but that is in part due to the fact that your desired result is not a valid python dictionary...



    but it may be a starting point for you to solve your problem.






    share|improve this answer



























      up vote
      1
      down vote



      accepted










      i was curious how i would do this and came up with this:



      lst = [['a', 'b', 'c'],
      ['a', 'c'],
      ['b']]

      tree = {}
      for branch in lst:
      count_str = 'count_*'
      last_node = branch[-1]
      cur_tree = tree
      for node in branch:
      if node == last_node:
      count_str = count_str[:-2] + f'_{node}'
      else:
      count_str = count_str[:-2] + f'_{node}_*'
      cur_tree[count_str] = cur_tree.get(count_str, 0) + 1
      cur_tree = cur_tree.setdefault(node, {})


      nothing special happening here...



      for your example:



      import json
      print(json.dumps(tree, sort_keys=True, indent=4))


      produces:



      {
      "a": {
      "b": {
      "c": {},
      "count_a_b_c": 1
      },
      "c": {},
      "count_a_b_*": 1,
      "count_a_c": 1
      },
      "b": {},
      "count_a_*": 2,
      "count_b": 1
      }


      it does not exactly reproduce what you imagine - but that is in part due to the fact that your desired result is not a valid python dictionary...



      but it may be a starting point for you to solve your problem.






      share|improve this answer

























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        i was curious how i would do this and came up with this:



        lst = [['a', 'b', 'c'],
        ['a', 'c'],
        ['b']]

        tree = {}
        for branch in lst:
        count_str = 'count_*'
        last_node = branch[-1]
        cur_tree = tree
        for node in branch:
        if node == last_node:
        count_str = count_str[:-2] + f'_{node}'
        else:
        count_str = count_str[:-2] + f'_{node}_*'
        cur_tree[count_str] = cur_tree.get(count_str, 0) + 1
        cur_tree = cur_tree.setdefault(node, {})


        nothing special happening here...



        for your example:



        import json
        print(json.dumps(tree, sort_keys=True, indent=4))


        produces:



        {
        "a": {
        "b": {
        "c": {},
        "count_a_b_c": 1
        },
        "c": {},
        "count_a_b_*": 1,
        "count_a_c": 1
        },
        "b": {},
        "count_a_*": 2,
        "count_b": 1
        }


        it does not exactly reproduce what you imagine - but that is in part due to the fact that your desired result is not a valid python dictionary...



        but it may be a starting point for you to solve your problem.






        share|improve this answer














        i was curious how i would do this and came up with this:



        lst = [['a', 'b', 'c'],
        ['a', 'c'],
        ['b']]

        tree = {}
        for branch in lst:
        count_str = 'count_*'
        last_node = branch[-1]
        cur_tree = tree
        for node in branch:
        if node == last_node:
        count_str = count_str[:-2] + f'_{node}'
        else:
        count_str = count_str[:-2] + f'_{node}_*'
        cur_tree[count_str] = cur_tree.get(count_str, 0) + 1
        cur_tree = cur_tree.setdefault(node, {})


        nothing special happening here...



        for your example:



        import json
        print(json.dumps(tree, sort_keys=True, indent=4))


        produces:



        {
        "a": {
        "b": {
        "c": {},
        "count_a_b_c": 1
        },
        "c": {},
        "count_a_b_*": 1,
        "count_a_c": 1
        },
        "b": {},
        "count_a_*": 2,
        "count_b": 1
        }


        it does not exactly reproduce what you imagine - but that is in part due to the fact that your desired result is not a valid python dictionary...



        but it may be a starting point for you to solve your problem.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 17 at 12:06

























        answered Nov 17 at 11:33









        hiro protagonist

        17.7k63660




        17.7k63660






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53350458%2fcreate-a-nested-tree-from-list%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            If I really need a card on my start hand, how many mulligans make sense? [duplicate]

            Alcedinidae

            Can an atomic nucleus contain both particles and antiparticles? [duplicate]