Writing a dictionary data to a file?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • psbasha
    Contributor
    • Feb 2007
    • 440

    Writing a dictionary data to a file?

    Hi,

    I would like to write the dictionary data to the file.

    The following stuff I am doing :

    Code:
          sampleDict = { 100:[1,2,3],200:[4.5,6], 300:[7,8,9]}
          list1 = sampleDict.keys()
           sf =  open("C:\\TestFiles\\Sample.txt",'w')        
            for i in range( 0, list1.__len__()):
                f.write(sampleDict t[i])
                f.write('\n')            
            f.close()
    I tried to get the size of the dictionary ( count = sampleDict.size ),but it is giving error,so I am using list in between.
    The out put should be

    100 1 2 3
    200 4 5 6
    300 7 8 9

    Could anybody help me in getting this output.

    Thanks in advance
    -PSB
  • dshimer
    Recognized Expert New Member
    • Dec 2006
    • 136

    #2
    Using the exact same dictionary but calling it d and not getting too tricky.
    Code:
    >>> f=open(r'c:/tmp/test.txt','w')
    >>> for i in d.keys():
    ... 	f.write(repr(i))
    ... 	for n in d[i]:
    ... 		f.write(' %s'%(repr(n)))
    ... 	f.write('\n')
    ... 
    >>> f.close()
    yields a file that looks like

    200 4.5 6
    300 7 8 9
    100 1 2 3
    Last edited by dshimer; Mar 7 '07, 10:19 PM. Reason: correct a mis-spelling

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Originally posted by psbasha
      Hi,

      I would like to write the dictionary data to the file.

      The following stuff I am doing :

      Code:
            sampleDict = { 100:[1,2,3],200:[4.5,6], 300:[7,8,9]}
            list1 = sampleDict.keys()
             sf =  open("C:\\TestFiles\\Sample.txt",'w')        
              for i in range( 0, list1.__len__()):
                  f.write(sampleDict t[i])
                  f.write('\n')            
              f.close()
      I tried to get the size of the dictionary ( count = sampleDict.size ),but it is giving error,so I am using list in between.
      The out put should be

      100 1 2 3
      200 4 5 6
      300 7 8 9

      Could anybody help me in getting this output.

      Thanks in advance
      -PSB
      As my friend dshimer points out, an extraction from the dictionary without the use of a sorted key list will result in arbitrary order of the result. And
      Code:
         
              for i in range( 0, list1.__len__()):
      should always be
      Code:
         
              for i in range( 0, len(list1)):
      or
      Code:
         
              for i in range(len(list1)):

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #4
        If all you are trying to do is persist a dictionary over time, you may want to check out the cpickle library module. The old pickle module is implemented in python. The cpickle module is much faster. They both offer a simple way to store (semi) encoded python object to disk.

        Comment

        • dshimer
          Recognized Expert New Member
          • Dec 2006
          • 136

          #5
          I am missing something. It seems to me that the whole range on len is a mis-step. Originally I was trying to point out that by simply "for" looping over the key list you could easily output the items. In retrospect I should have
          Code:
          list1 = sampleDict.keys()
          list1.sort()
          for i in list1:
          to sort the order, but now that I look at it, I don't understand the
          Code:
          f.write(sampleDict t[i])
          line. What does that t[i] do?

          Comment

          • bartonc
            Recognized Expert Expert
            • Sep 2006
            • 6478

            #6
            Originally posted by dshimer
            I am missing something. It seems to me that the whole range on len is a mis-step. Originally I was trying to point out that by simply "for" looping over the key list you could easily output the items. In retrospect I should have
            Code:
            list1 = sampleDict.keys()
            list1.sort()
            for i in list1:
            to sort the order, but now that I look at it, I don't understand the
            Code:
            f.write(sampleDict t[i])
            line. What does that t[i] do?
            Yep. Your way is WAY better. I think that PSB was making a guess and all I was doing was pointing out improper use if internals method.

            Comment

            • bvdet
              Recognized Expert Specialist
              • Oct 2006
              • 2851

              #7
              Originally posted by dshimer
              I am missing something. It seems to me that the whole range on len is a mis-step. Originally I was trying to point out that by simply "for" looping over the key list you could easily output the items. In retrospect I should have
              Code:
              list1 = sampleDict.keys()
              list1.sort()
              for i in list1:
              to sort the order, but now that I look at it, I don't understand the
              Code:
              f.write(sampleDict t[i])
              line. What does that t[i] do?
              I think he made a typo. It should be
              Code:
              f.write(sampleDict[i])
              I have a version:
              Code:
              f = open("your_file",'w')
              for key in sorted(dd):
                  f.write('%s %s\n' % (str(key), ''.join(repr(dd[key]).strip('[]').split(','))))
              f.close()

              Comment

              • joshbwhite
                New Member
                • Dec 2007
                • 1

                #8
                I use this method to read and write a python dictionary to file.
                >> d = {"names":['yar','har','ga r'],"places":['far','near','m ars']}
                >> file('dict.txt' ,'w').write(rep r(a))

                Then when I want it back on another run

                >> r = file('dict.txt' ,'r').read()
                >> d = eval(r)

                Comment

                • aeneng
                  New Member
                  • Aug 2011
                  • 1

                  #9
                  Originally posted by joshbwhite
                  I use this method to read and write a python dictionary to file.
                  >> d = {"names":['yar','har','ga r'],"places":['far','near','m ars']}
                  >> file('dict.txt' ,'w').write(rep r(a))

                  Then when I want it back on another run

                  >> r = file('dict.txt' ,'r').read()
                  >> d = eval(r)
                  This is very useful to store the dictionary.

                  Comment

                  Working...