Inserting in multidimension dictionary.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bharathpaul
    New Member
    • Mar 2010
    • 6

    Inserting in multidimension dictionary.

    I am working with python 3.1.1 Below is my code and this works well.
    Code:
    dict={'paul':{'age':23,'hobby':'computer','like':'music'}}
    print (dict['paul']['hobby'])
    But how to insert a new item in the above dictionary.
    If i tried with, say
    dict['anotheritem']['nested']='true' , it gives error...
    Also help me in printing the elements using Loop
    Last edited by bvdet; Mar 9 '10, 12:17 PM. Reason: Add code tags
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Hi

    There may be a better way to do this, but in general I've always added the outer dictionary and then populated it.

    (BTW better not to use dict, since it's taken! I've changed it to myDict below)

    Code:
    myDict['anotheritem']=dict() #creates empty dictionary
    myDict['anotheritem']['nested']=True #populated new dictionary
    Regarding the printing:
    Code:
    for d1 in myDict:
        for d2 in myDict[d1]:
            print d1, d2, myDict[d2]
    should work (ie I haven't tried it out)

    Good luck, and please post back to tell us how it goes...

    Comment

    • bharathpaul
      New Member
      • Mar 2010
      • 6

      #3
      Thanks. Its working. But to print, its not working.so i've used the below code to print
      Code:
      mydict=dict()
      mydict['a']=dict()
      mydict['a']['nested']=True
      for key1,value1 in mydict.items():
          tempdict = dict(mydict[key1].items())
          for key,value in tempdict.items():
             print (key1,key,value)
      And This is working good....
      Thanks once again
      Last edited by bvdet; Mar 9 '10, 02:01 PM. Reason: Add code tags

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        bharathpaul,

        Please use code tags when posting code. See posting guidelines here.

        BV - Moderator

        Comment

        • Glenton
          Recognized Expert Contributor
          • Nov 2008
          • 391

          #5
          Oh, sorry. This is what you get when you don't run the code. It should be:
          Code:
          for d1 in myDict:
              for d2 in myDict[d1]:
                  print d1, d2, myDict[d1][d2]
          But you got the idea, and solved it yourself, which is great!

          Comment

          Working...