473,398 Members | 2,188 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Writing a dictionary data to a file?

440 256MB
Hi,

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

The following stuff I am doing :

Expand|Select|Wrap|Line Numbers
  1.       sampleDict = { 100:[1,2,3],200:[4.5,6], 300:[7,8,9]}
  2.       list1 = sampleDict.keys()
  3.        sf =  open("C:\\TestFiles\\Sample.txt",'w')        
  4.         for i in range( 0, list1.__len__()):
  5.             f.write(sampleDict t[i])
  6.             f.write('\n')            
  7.         f.close()
  8.  
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
Mar 7 '07 #1
8 27023
dshimer
136 Expert 100+
Using the exact same dictionary but calling it d and not getting too tricky.
Expand|Select|Wrap|Line Numbers
  1. >>> f=open(r'c:/tmp/test.txt','w')
  2. >>> for i in d.keys():
  3. ...     f.write(repr(i))
  4. ...     for n in d[i]:
  5. ...         f.write(' %s'%(repr(n)))
  6. ...     f.write('\n')
  7. ... 
  8. >>> f.close()
yields a file that looks like

200 4.5 6
300 7 8 9
100 1 2 3
Mar 7 '07 #2
bartonc
6,596 Expert 4TB
Hi,

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

The following stuff I am doing :

Expand|Select|Wrap|Line Numbers
  1.       sampleDict = { 100:[1,2,3],200:[4.5,6], 300:[7,8,9]}
  2.       list1 = sampleDict.keys()
  3.        sf =  open("C:\\TestFiles\\Sample.txt",'w')        
  4.         for i in range( 0, list1.__len__()):
  5.             f.write(sampleDict t[i])
  6.             f.write('\n')            
  7.         f.close()
  8.  
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
Expand|Select|Wrap|Line Numbers
  1.  
  2.         for i in range( 0, list1.__len__()):
should always be
Expand|Select|Wrap|Line Numbers
  1.  
  2.         for i in range( 0, len(list1)):
or
Expand|Select|Wrap|Line Numbers
  1.  
  2.         for i in range(len(list1)):
Mar 7 '07 #3
bartonc
6,596 Expert 4TB
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.
Mar 8 '07 #4
dshimer
136 Expert 100+
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
Expand|Select|Wrap|Line Numbers
  1. list1 = sampleDict.keys()
  2. list1.sort()
  3. for i in list1:
to sort the order, but now that I look at it, I don't understand the
Expand|Select|Wrap|Line Numbers
  1. f.write(sampleDict t[i])
line. What does that t[i] do?
Mar 8 '07 #5
bartonc
6,596 Expert 4TB
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
Expand|Select|Wrap|Line Numbers
  1. list1 = sampleDict.keys()
  2. list1.sort()
  3. for i in list1:
to sort the order, but now that I look at it, I don't understand the
Expand|Select|Wrap|Line Numbers
  1. 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.
Mar 8 '07 #6
bvdet
2,851 Expert Mod 2GB
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
Expand|Select|Wrap|Line Numbers
  1. list1 = sampleDict.keys()
  2. list1.sort()
  3. for i in list1:
to sort the order, but now that I look at it, I don't understand the
Expand|Select|Wrap|Line Numbers
  1. f.write(sampleDict t[i])
line. What does that t[i] do?
I think he made a typo. It should be
Expand|Select|Wrap|Line Numbers
  1. f.write(sampleDict[i])
I have a version:
Expand|Select|Wrap|Line Numbers
  1. f = open("your_file",'w')
  2. for key in sorted(dd):
  3.     f.write('%s %s\n' % (str(key), ''.join(repr(dd[key]).strip('[]').split(','))))
  4. f.close()
Mar 8 '07 #7
I use this method to read and write a python dictionary to file.
>> d = {"names":['yar','har','gar'],"places":['far','near','mars']}
>> file('dict.txt','w').write(repr(a))

Then when I want it back on another run

>> r = file('dict.txt','r').read()
>> d = eval(r)
Dec 14 '07 #8
aeneng
1
@joshbwhite
This is very useful to store the dictionary.
Aug 22 '11 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Julian Yap | last post by:
Hi all, I'm trying to get some ideas on the best way to do this. In this particular coding snippet, I was thinking of creating a dictionary of file objects and file names. These would be...
4
by: Igor Shulgin | last post by:
Hi! What is standard and direct way (within Oracle 9.2 stored procedures) for writing binary data from Oracle to external file on disk? We have tried to use UTL_FILE package, but it operates on...
1
by: Daniel | last post by:
when writing out a file from .net, when is the file created? after the bytes are all written to the hard drive or before the bytes are written to the hard drive?
0
by: Yunus's Group | last post by:
Yunus's Group May 23, 3:36 pm show options Newsgroups: microsoft.public.dotnet.languages.vb From: "Yunus's Group" <yunusasm...@gmail.com> - Find messages by this author Date: 23 May 2005...
12
by: Steven Bethard | last post by:
Ok, so I have a module that is basically a Python wrapper around a big lookup table stored in a text file. The module needs to provide a few functions:: get_stem(word, pos, default=None)...
3
by: James Wong | last post by:
Hi, I have some XML config file in my VB project. When I use clickonce to publish my project, the execute files and the xml data files are not in the same folder of the client computer. How...
42
by: psbasha | last post by:
Hi, Is it necessary in Python to close the File after reading or writing the data to file?.While refering to Python material ,I saw some where mentioning that no need to close the file.Correct me...
10
by: Terry Olsen | last post by:
I need to be able to write to a file simultaneously from approximately 4 different threads. I'm working on a program that will download parts of a file and combine the parts. Each thread will have...
16
by: ravi | last post by:
I want to implement a dictionary data structure with the features features * autocorrect * autocomplete * spellcheck can any body tell me that which data structure will be best for its...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.