473,386 Members | 1,674 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,386 software developers and data experts.

Best way to create a Dictionary from file of Key-Value pairs?

Hi,

Assume I'm given a 100k file full of key-value pairs:

date,value
26-Feb-04,36.47
25-Feb-04,36.43
24-Feb-04,36.30
23-Feb-04,37.00
20-Feb-04,37.00
19-Feb-04,37.87

What is the best way to copy this data into a Dictionary object?

-moi
Jul 18 '05 #1
6 4702
On 2004-02-29 15:22:32 -0500, ir***@yahoo.com (Equis Uno) said:
Hi,

Assume I'm given a 100k file full of key-value pairs:

date,value
26-Feb-04,36.47
25-Feb-04,36.43
24-Feb-04,36.30
23-Feb-04,37.00
20-Feb-04,37.00
19-Feb-04,37.87

What is the best way to copy this data into a Dictionary object?


Getting that data into a dictionary is the easy part.. deciding how
you want to use it is much harder.

Python 2.3 comes with a module designed specifically to read files that
look like that, so here's a start:

# none of this code is tested
import csv
myfile = file('myfilename')
myfile.readline() # skip "date,value" line
datevaluemap = dict(csv.reader(myfile))

But your dates and values would end up as strings.. so you might want
to do something like
datevaluemap = dict([(key, float(value)) for (key, value) in
csv.reader(myfile)])

Which would get your values in as floats, not strings. The dates would
still be strings though, and you might want to use a datetime.date
object for that. I don't want to demonstrate how to convert those too,
since it's longer, uglier, and I don't know strftime format codes off
the top of my head.. but you can look into datetime.date and
time.strptime.

-bob

Jul 18 '05 #2

"Equis Uno" <ir***@yahoo.com> schrieb im Newsbeitrag
news:69**************************@posting.google.c om...
| Hi,
|
| Assume I'm given a 100k file full of key-value pairs:
|
| date,value
| 26-Feb-04,36.47
| 25-Feb-04,36.43
| 24-Feb-04,36.30
| 23-Feb-04,37.00
| 20-Feb-04,37.00
| 19-Feb-04,37.87
|
| What is the best way to copy this data into a Dictionary object?

If it suffices ro generate a "string-to-string mapping", you could do:
d = {}
for line in file("infile"):

k, v = line.rstrip().split(",")
d[k] = v

This will give you:

{'20-Feb-04': '37.00', '19-Feb-04': '37.87', '26-Feb-04': '36.47',
'23-Feb-04': '37.00', '25-Feb-04': '36.43', '24-Feb-04': '36.30'}

HTH,
Vincent Wehren

|
| -moi
Jul 18 '05 #3
"Equis Uno" <ir***@yahoo.com> wrote in message
news:69**************************@posting.google.c om...
Hi,

Assume I'm given a 100k file full of key-value pairs:

date,value
26-Feb-04,36.47
25-Feb-04,36.43
24-Feb-04,36.30
23-Feb-04,37.00
20-Feb-04,37.00
19-Feb-04,37.87

What is the best way to copy this data into a Dictionary object?

-moi


Here's one way:

d = dict([l.strip().split(',') for l in open(fname)])

This opens the file, reads one line at a time, trims the beginning and end
of the line, splits the line at the comma delimiter - your key-value pairs -
and builds a list of these key-value pairs which is then used by dict() to
make a new dictionary. This is not really a robust solution, but you get the
idea. Your solution may require more processing if you want the values to be
floats (for example) or if there might be blank lines or extra white space
in the data, or whatever other issues you may want to guard against. Plus,
you may want to move the open() operation outside of the list comprehension
so you can check/handle possible errors (like file not found, for instance),
as well as close the file, that sort of thing ...

HTH,
Sean
Jul 18 '05 #4

"Equis Uno" <ir***@yahoo.com> wrote in message
news:69**************************@posting.google.c om...
Hi,

Assume I'm given a 100k file full of key-value pairs:

date,value
26-Feb-04,36.47
25-Feb-04,36.43
24-Feb-04,36.30
23-Feb-04,37.00
20-Feb-04,37.00
19-Feb-04,37.87

What is the best way to copy this data into a Dictionary object?


If you really have one value for each of numerous sequential dates, you
might be better off putting values in list that is attribute of class also
with start and stop date attributes.

TJR


Jul 18 '05 #5

Equis> Assume I'm given a 100k file full of key-value pairs:

Equis> date,value
Equis> 26-Feb-04,36.47
Equis> 25-Feb-04,36.43
Equis> 24-Feb-04,36.30
Equis> 23-Feb-04,37.00
Equis> 20-Feb-04,37.00
Equis> 19-Feb-04,37.87

Equis> What is the best way to copy this data into a Dictionary object?

Maybe overkill, but you have a csv file. I'd use the csv module (new in
2.3):

import csv

d = {}
rdr = csv.DictReader(file("source-file"))
for row in rdr:
d[row["date"]] = row["value"]

Skip

Jul 18 '05 #6
I must say, CLP rocks.

I added some syntax to convert the key from string to a time data
type:

import time
# Convert the values to float and the keys to time
myfile = file('csvData.txt')
myfile.readline() # skip "date,value" line
datevaluemap = dict([( time.strptime(key, '%d-%b-%y'), float(value))
for (key, value) in csv.reader(myfile)])
print datevaluemap

output:

{(2004, 2, 24, 0, 0, 0, 1, 55, -1): 36.299999999999997, (2004, 2, 19,
0, 0, 0, 3, 50, -1): 37.869999999999997, (2004, 2, 26, 0, 0, 0, 3, 57,
-1): 36.469999999999999, (2004, 2, 20, 0, 0, 0, 4, 51, -1): 37.0,
(2004, 2, 23, 0, 0, 0, 0, 54, -1): 37.0, (2004, 2, 25, 0, 0, 0, 2, 56,
-1): 36.43}

I'm way happy!

-moi
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Karthikesh Raju | last post by:
Hi All, i am wondering about the best way to read in a configuration file that goes like: ########### source_dir = '/home/karthik/Projects/python' data_dir =...
4
by: brianobush | last post by:
# # My problem is that I want to create a # class, but the variables aren't known # all at once. So, I use a dictionary to # store the values in temporarily. # Then when I have a complete set, I...
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...
2
by: ESPNSTI | last post by:
Hi, I'm trying to use a generics dictionary with a key class that implements and needs IComparable<>. However when I attempt to use the dictionary, it doesn't appear to use the IComparable<> to...
5
by: Brian Richards | last post by:
I'm experiencing some wierd behavior with a Dictionary<T,U> class using foreach loops, such that the Key returned in the foreach is not contained in the dictionary. code: Dictionary<A, B>...
10
by: Petr Jakeš | last post by:
I have a standard 12-key mobile phone keypad connected to my Linux machine as a I2C peripheral. I would like to write a code which allows the text entry to the computer using this keypad (something...
14
by: erikcw | last post by:
Hi, I'm trying to turn o list of objects into a dictionary using a list comprehension. Something like entries = {} = d.id] for d in links]
2
by: =?Utf-8?B?U2hhd24=?= | last post by:
Hi; I would like to be able to use the XMLSerializer to serialize and deserialize a dictionary. is that possible? i know that you can serialize an object that implements the ICollection interface....
8
by: Bob Altman | last post by:
Hi all, I'm trying to do something that should be really easy, but I can't think of an obvious way to do it. I have a dictionary whose value is a "value type" (as opposed to a reference type --...
3
by: =?Utf-8?B?THVpZ2k=?= | last post by:
Hi all, I have a dictionary (C# 2.0) with an object (an instance of a class) for the key. The class has only a "name" field. dictionary<object, ...> When I use ContainsKey property of the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...

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.