Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8982275
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T20:32:24+00:00 2026-06-15T20:32:24+00:00

I have a nested list that I need to convert into a hierarchical dictionary.

  • 0

I have a nested list that I need to convert into a hierarchical dictionary. However I am a bit confused how to achieve it in a clean pythonic way. Here’s a somewhat ugly sample code that I have come up with. How to improve it?

from itertools import tee,izip
import json

L=[(1,2,3,4,5),(1,2,7),(2,3,5),(3,4,5,6)]

def pairs(iterable):
    a,b = tee(iterable)
    b.next()
    return izip(a,b)

def innerfunc(pairs,d):
    try:
        pair           = pairs.next()
        item, nextitem = pair        
    except StopIteration:       
        return 
    if item in d:        
        innerfunc(pairs,d[item])
    else:        
        d[item]= {}
        {nextitem : innerfunc(pairs,d[item])}


def outerfunc(matrix):
    result_dict={}
    for row in matrix:        
        iter_pairs = pairs(row+(0,))
        innerfunc(iter_pairs,result_dict)
    return result_dict

print json.dumps(outerfunc(L), sort_keys=True, indent=4)

Output:

{
    "1": {
        "2": {
            "3": {
                "4": {
                    "5": {}
                }
            }, 
            "7": {}
        }
    }, 
    "2": {
        "3": {
            "5": {}
        }
    }, 
    "3": {
        "4": {
            "5": {
                "6": {}
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T20:32:26+00:00Added an answer on June 15, 2026 at 8:32 pm

    You can do that quite succinctly using recursion:

    def append_path(root, paths):
        if paths:
            child = root.setdefault(paths[0], {})
            append_path(child, paths[1:])
    
    # Example usage
    root = {}
    for p in [(1,2,3,4,5),(1,2,7),(2,3,5),(3,4,5,6)]:
        append_path(root, p)
    
    # Print results
    import json
    print json.dumps(root,  indent=4)
    

    Output:

    {
        "1": {
            "2": {
                "3": {
                    "4": {
                        "5": {}
                    }
                }, 
                "7": {}
            }
        }, 
        "2": {
            "3": {
                "5": {}
            }
        }, 
        "3": {
            "4": {
                "5": {
                    "6": {}
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a list that contains nested lists and I need to know the
I need to transform large XML files that have a nested (hierarchical) structure of
I have Python nested list that I'm trying to organize and eventually count number
Little help need with jquery sortable. I have a nested list like so: <div
I have a dictionary that I've converted to a list so I can sort
I have a sencha nested list that contains some elements from a store. I
I have a nested repeater control that displays a list of data, in my
I need to convert a String representation of a nested List back to a
I have nested list of the following form: my_list = [['Some1', '2', '3.6', '4.5',
I have a nested list like this: <ul class=list> <li class=list_item_type_1> <ul class=list> <li

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.