473,320 Members | 2,124 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,320 software developers and data experts.

file to dictionary

31
i am given an open file in the form of, key serperator value, its not just 1 line but many lines in that form. what the objective is is that i have to convert the open file into a dictionary where the output should be {key : value}, and the seperator is where it splits it up into both values.

for example:

File:
abc def ghj
jkl def jkk
uio def asd

the output should be :{"abc": "ghj" , "jkl" : "jkk", "uio" : "asd"}

and the parameters should be:

def file_to_dict(file, seperator)

How would i write a file like this any hints?
Mar 11 '09 #1
5 3136
bvdet
2,851 Expert Mod 2GB
Have you tried to code this yourself? Maybe this will give you some hints:
Expand|Select|Wrap|Line Numbers
  1. s = '''
  2. abc def ghj
  3. jkl def jkk
  4. uio def asd
  5. '''
  6.  
  7. sList = [item for item in s.split('\n') if item]
  8.  
  9. sep = "def"
  10. dd = {}
  11. for item in sList:
  12.     a,b = item.split(sep)
  13.     dd[a.strip()] = b.strip()
Mar 11 '09 #2
v13tn1g
31
yep i've tried to code it myself but what i have so far is i've basically made the file into a string and then in split it using the seperator. it's just that now im stuck with the word before the seperator as the key and after the seperator as the value.
Mar 11 '09 #3
v13tn1g
31
Expand|Select|Wrap|Line Numbers
  1. import urllib
  2.  
  3. def file_to_dict(a, s):
  4.     '''Return a dictionary that contains the contents of each line in a given 
  5.     open file as a key-value pair. The file contains lines of the form key 
  6.     separator value, where separator is the second parameter of the function. 
  7.     There may be more than one occurrence of the separator in the line; 
  8.     the key is before the first one - all others are part of the value string.
  9.     Both key and value shoud be without leading or trailing whitespace. '''
  10.  
  11.     f = urllib.urlopen(a)
  12.     for c in f:
  13.         g = c.rstrip()
  14.  
  15.     sList = [item for item in g.split('\n') if item]
  16.  
  17.     sep = s
  18.     dd = {}
  19.     for item in sList:
  20.         a,b = item.split(s)
  21.         dd[a.strip()] = b.strip()
  22.     print dd

I test it with:

Expand|Select|Wrap|Line Numbers
  1. file_to_dict("http://www.utsc.utoronto.ca/~szamosi/a20/lectures/w2/price_1.py", "price")
but i get the error

Expand|Select|Wrap|Line Numbers
  1. File "y:\<string>", line 1, in <module>
  2.   File "y:\<string>", line 34, in file_to_dict
  3. ValueError: too many values to unpack
Mar 14 '09 #4
v13tn1g
31
@bvdet
I think i know why i got that error, its because i tested a file such as

Expand|Select|Wrap|Line Numbers
  1. s = '''
  2. dfs ghj hge
  3. abc def ghj
  4. jkl def jkk
  5. uio def asd
  6. '''
the first line did not have the seperator hence the error.

also another thing if the test file were to be

Expand|Select|Wrap|Line Numbers
  1. s = '''
  2. dfs ghj hge
  3. abc def ghj
  4. jkl def jkk
  5. uio def asd
  6. dfs def qwe
  7. '''
since there is 2 occurances of dfs it won't print both of them in the dictionary it will only print out one, how should i write this program to print out both "dfs" key and value?
Mar 14 '09 #5
bvdet
2,851 Expert Mod 2GB
The first line has no separator, therefore the ValueError. We can trap that with a try/except block. Since we can have more than one data element with the same key, create a list for the values.
Expand|Select|Wrap|Line Numbers
  1. s = '''
  2.  
  3. dfs ghj hge
  4. abc def ghj
  5. jkl def jkk
  6. uio def asd
  7. dfs def qwe
  8. dfs def ewq
  9.  
  10.  
  11. '''
  12.  
  13.  
  14. sList = [item for item in s.split('\n') if item.strip()]
  15.  
  16. sep = "def"
  17. dd = {}
  18. for i, item in enumerate(sList):
  19.     try:
  20.         a,b = [s.strip() for s in item.split(sep)]
  21.         dd.setdefault(a, []).append(b)
  22.     except ValueError, e:
  23.         print "Malformed data line number %d" % (i+1)
  24.  
  25. for key in dd:
  26.     for item in dd[key]:
  27.         print "%s: %s" % (key, item)
Output:
Expand|Select|Wrap|Line Numbers
  1. >>> Malformed data line number 1
  2. jkl: jkk
  3. abc: ghj
  4. dfs: qwe
  5. dfs: ewq
  6. uio: asd
  7. >>> 
Mar 14 '09 #6

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

Similar topics

4
by: Fuzzyman | last post by:
There have been a couple of config file 'systems' announced recently, that focus on building more powerful and complex configuration files. ConfigObj is a module to enable you to much more *simply*...
10
by: Luis P. Mendes | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, my program builds a dictionary that I would like to save in a file. My question is what are the simple ways to do it? The first solution...
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...
1
by: laredotornado | last post by:
Hello, I want to play an audio file embedded on my page by clicking on an audio image and the page change to a new page. Is there a cross-browser Javascript way to do this? Right now the code I...
0
by: laredotornado | last post by:
Hello, I want to play an audio file by clicking on an audio icon and not having the page switch out underneath. Right now the code I have is ... <html> <head> <title>Dictionary:...
12
by: teoryn | last post by:
I've been spending today learning python and as an exercise I've ported a program I wrote in java that unscrambles a word. Before describing the problem, here's the code: *--beginning of file--*...
5
by: rohit | last post by:
i want to implement a dictionary in python the query is : without explicitly doing the following steps 1. reading from file to list 2. processing list to dictionary is there a module or a built...
3
GTXY20
by: GTXY20 | last post by:
Hi All, I have been able to create a successful application with Python but I am being asked to create in VB. I have a text file with the following data: 1,a 1,b 1,c 2,a
0
GTXY20
by: GTXY20 | last post by:
Hi all, I currently have a CSV file like so 1,a 1,b 1,c 2,a 2,b 2,b
1
by: jim-on-linux | last post by:
On Saturday 14 June 2008 03:15, Beema shafreen wrote: I have used this method to solve similar problems. This is a consept of how to do what you want, but you will have to work a little to...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.