Reading lines from text and converting it into Python nested dictionary











up vote
1
down vote

favorite












So i have the below text as an input file:



A B 1
A C 2
B C 1
B D 3
B E 2
C D 1
C E 2
D E 4
D F 3
E F 3


and i want to store all these values in a nested dictionary in python:



{ 'A': {'B': 1, 'C': 2},
'B': {'C': 1, 'D': 3, 'E': 2},
'C': {'D': 1, 'E': 2},
'D': {'E': 4, 'F': 3},
'E': {'F': 3} }


This is my code which is reading an input file and trying to convert it into a nested dictionary



inputfile = open("input.txt", "r")
lines = inputfile.readlines()
edges =
for line in lines:
edges.append(line.split())
d = {}
nn={}

for i in edges:
nn.update({i[1]:i[2]})
d[i[0]] = nn
index+=1

print(d)


This is my incorrect output



{'A': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'B': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'C': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'D': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'E': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}}


I am looking for a correct if else condition which will update the dict items when the key is same and append if it is different. Thanks in advance.










share|improve this question




























    up vote
    1
    down vote

    favorite












    So i have the below text as an input file:



    A B 1
    A C 2
    B C 1
    B D 3
    B E 2
    C D 1
    C E 2
    D E 4
    D F 3
    E F 3


    and i want to store all these values in a nested dictionary in python:



    { 'A': {'B': 1, 'C': 2},
    'B': {'C': 1, 'D': 3, 'E': 2},
    'C': {'D': 1, 'E': 2},
    'D': {'E': 4, 'F': 3},
    'E': {'F': 3} }


    This is my code which is reading an input file and trying to convert it into a nested dictionary



    inputfile = open("input.txt", "r")
    lines = inputfile.readlines()
    edges =
    for line in lines:
    edges.append(line.split())
    d = {}
    nn={}

    for i in edges:
    nn.update({i[1]:i[2]})
    d[i[0]] = nn
    index+=1

    print(d)


    This is my incorrect output



    {'A': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'B': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'C': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'D': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'E': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}}


    I am looking for a correct if else condition which will update the dict items when the key is same and append if it is different. Thanks in advance.










    share|improve this question


























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      So i have the below text as an input file:



      A B 1
      A C 2
      B C 1
      B D 3
      B E 2
      C D 1
      C E 2
      D E 4
      D F 3
      E F 3


      and i want to store all these values in a nested dictionary in python:



      { 'A': {'B': 1, 'C': 2},
      'B': {'C': 1, 'D': 3, 'E': 2},
      'C': {'D': 1, 'E': 2},
      'D': {'E': 4, 'F': 3},
      'E': {'F': 3} }


      This is my code which is reading an input file and trying to convert it into a nested dictionary



      inputfile = open("input.txt", "r")
      lines = inputfile.readlines()
      edges =
      for line in lines:
      edges.append(line.split())
      d = {}
      nn={}

      for i in edges:
      nn.update({i[1]:i[2]})
      d[i[0]] = nn
      index+=1

      print(d)


      This is my incorrect output



      {'A': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'B': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'C': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'D': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'E': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}}


      I am looking for a correct if else condition which will update the dict items when the key is same and append if it is different. Thanks in advance.










      share|improve this question















      So i have the below text as an input file:



      A B 1
      A C 2
      B C 1
      B D 3
      B E 2
      C D 1
      C E 2
      D E 4
      D F 3
      E F 3


      and i want to store all these values in a nested dictionary in python:



      { 'A': {'B': 1, 'C': 2},
      'B': {'C': 1, 'D': 3, 'E': 2},
      'C': {'D': 1, 'E': 2},
      'D': {'E': 4, 'F': 3},
      'E': {'F': 3} }


      This is my code which is reading an input file and trying to convert it into a nested dictionary



      inputfile = open("input.txt", "r")
      lines = inputfile.readlines()
      edges =
      for line in lines:
      edges.append(line.split())
      d = {}
      nn={}

      for i in edges:
      nn.update({i[1]:i[2]})
      d[i[0]] = nn
      index+=1

      print(d)


      This is my incorrect output



      {'A': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'B': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'C': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'D': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'E': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}}


      I am looking for a correct if else condition which will update the dict items when the key is same and append if it is different. Thanks in advance.







      python python-3.x dictionary






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 at 0:35









      dawg

      57.1k1179151




      57.1k1179151










      asked Nov 11 at 0:22









      Sahil Sood

      183




      183
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          You can do:



          di={}
          with open(fn) as f_in:
          for line in f_in:
          li=line.split()
          di.setdefault(li[0],{})[li[1]]=li[2]

          >>> di
          {'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}





          share|improve this answer




























            up vote
            0
            down vote













            You can use recursion with collections.defaultdict:



            import collections
            def group(d):
            _d = collections.defaultdict(list)
            for a, *b in d:
            _d[a].append(b)
            return {a:group(b) if len(b) > 1 else dict(b) if len(b[0]) > 1 else b[0][0] for a, b in _d.items()}

            content = [i.strip('n').split() for i in open('filename.txt')]
            final_result = group(content)


            Output:



            {'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}


            This will also work on larger input samples:



            s = """
            A B C D
            A C D E
            A H I F
            B D T G
            B F E H
            B U F A
            """
            content = [i.split() for i in filter(None, s.split('n'))]
            print(group(content))


            Output:



            {'A': {'B': {'C': 'D'}, 'C': {'D': 'E'}, 'H': {'I': 'F'}}, 'B': {'D': {'T': 'G'}, 'F': {'E': 'H'}, 'U': {'F': 'A'}}}





            share|improve this answer























            • Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
              – Sahil Sood
              Nov 11 at 0:54











            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%2f53244723%2freading-lines-from-text-and-converting-it-into-python-nested-dictionary%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            You can do:



            di={}
            with open(fn) as f_in:
            for line in f_in:
            li=line.split()
            di.setdefault(li[0],{})[li[1]]=li[2]

            >>> di
            {'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}





            share|improve this answer

























              up vote
              1
              down vote



              accepted










              You can do:



              di={}
              with open(fn) as f_in:
              for line in f_in:
              li=line.split()
              di.setdefault(li[0],{})[li[1]]=li[2]

              >>> di
              {'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}





              share|improve this answer























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                You can do:



                di={}
                with open(fn) as f_in:
                for line in f_in:
                li=line.split()
                di.setdefault(li[0],{})[li[1]]=li[2]

                >>> di
                {'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}





                share|improve this answer












                You can do:



                di={}
                with open(fn) as f_in:
                for line in f_in:
                li=line.split()
                di.setdefault(li[0],{})[li[1]]=li[2]

                >>> di
                {'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 11 at 0:30









                dawg

                57.1k1179151




                57.1k1179151
























                    up vote
                    0
                    down vote













                    You can use recursion with collections.defaultdict:



                    import collections
                    def group(d):
                    _d = collections.defaultdict(list)
                    for a, *b in d:
                    _d[a].append(b)
                    return {a:group(b) if len(b) > 1 else dict(b) if len(b[0]) > 1 else b[0][0] for a, b in _d.items()}

                    content = [i.strip('n').split() for i in open('filename.txt')]
                    final_result = group(content)


                    Output:



                    {'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}


                    This will also work on larger input samples:



                    s = """
                    A B C D
                    A C D E
                    A H I F
                    B D T G
                    B F E H
                    B U F A
                    """
                    content = [i.split() for i in filter(None, s.split('n'))]
                    print(group(content))


                    Output:



                    {'A': {'B': {'C': 'D'}, 'C': {'D': 'E'}, 'H': {'I': 'F'}}, 'B': {'D': {'T': 'G'}, 'F': {'E': 'H'}, 'U': {'F': 'A'}}}





                    share|improve this answer























                    • Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
                      – Sahil Sood
                      Nov 11 at 0:54















                    up vote
                    0
                    down vote













                    You can use recursion with collections.defaultdict:



                    import collections
                    def group(d):
                    _d = collections.defaultdict(list)
                    for a, *b in d:
                    _d[a].append(b)
                    return {a:group(b) if len(b) > 1 else dict(b) if len(b[0]) > 1 else b[0][0] for a, b in _d.items()}

                    content = [i.strip('n').split() for i in open('filename.txt')]
                    final_result = group(content)


                    Output:



                    {'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}


                    This will also work on larger input samples:



                    s = """
                    A B C D
                    A C D E
                    A H I F
                    B D T G
                    B F E H
                    B U F A
                    """
                    content = [i.split() for i in filter(None, s.split('n'))]
                    print(group(content))


                    Output:



                    {'A': {'B': {'C': 'D'}, 'C': {'D': 'E'}, 'H': {'I': 'F'}}, 'B': {'D': {'T': 'G'}, 'F': {'E': 'H'}, 'U': {'F': 'A'}}}





                    share|improve this answer























                    • Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
                      – Sahil Sood
                      Nov 11 at 0:54













                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    You can use recursion with collections.defaultdict:



                    import collections
                    def group(d):
                    _d = collections.defaultdict(list)
                    for a, *b in d:
                    _d[a].append(b)
                    return {a:group(b) if len(b) > 1 else dict(b) if len(b[0]) > 1 else b[0][0] for a, b in _d.items()}

                    content = [i.strip('n').split() for i in open('filename.txt')]
                    final_result = group(content)


                    Output:



                    {'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}


                    This will also work on larger input samples:



                    s = """
                    A B C D
                    A C D E
                    A H I F
                    B D T G
                    B F E H
                    B U F A
                    """
                    content = [i.split() for i in filter(None, s.split('n'))]
                    print(group(content))


                    Output:



                    {'A': {'B': {'C': 'D'}, 'C': {'D': 'E'}, 'H': {'I': 'F'}}, 'B': {'D': {'T': 'G'}, 'F': {'E': 'H'}, 'U': {'F': 'A'}}}





                    share|improve this answer














                    You can use recursion with collections.defaultdict:



                    import collections
                    def group(d):
                    _d = collections.defaultdict(list)
                    for a, *b in d:
                    _d[a].append(b)
                    return {a:group(b) if len(b) > 1 else dict(b) if len(b[0]) > 1 else b[0][0] for a, b in _d.items()}

                    content = [i.strip('n').split() for i in open('filename.txt')]
                    final_result = group(content)


                    Output:



                    {'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}


                    This will also work on larger input samples:



                    s = """
                    A B C D
                    A C D E
                    A H I F
                    B D T G
                    B F E H
                    B U F A
                    """
                    content = [i.split() for i in filter(None, s.split('n'))]
                    print(group(content))


                    Output:



                    {'A': {'B': {'C': 'D'}, 'C': {'D': 'E'}, 'H': {'I': 'F'}}, 'B': {'D': {'T': 'G'}, 'F': {'E': 'H'}, 'U': {'F': 'A'}}}






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 11 at 0:37

























                    answered Nov 11 at 0:27









                    Ajax1234

                    38.8k42452




                    38.8k42452












                    • Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
                      – Sahil Sood
                      Nov 11 at 0:54


















                    • Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
                      – Sahil Sood
                      Nov 11 at 0:54
















                    Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
                    – Sahil Sood
                    Nov 11 at 0:54




                    Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
                    – Sahil Sood
                    Nov 11 at 0:54


















                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244723%2freading-lines-from-text-and-converting-it-into-python-nested-dictionary%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

                    Florida Star v. B. J. F.

                    Danny Elfman

                    Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues