We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,451 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Fixing function problem

Hi all,

I am trying to use the following python code to read data from two .csv files which have data in the following format, e.g.

1, 23.27, 23.21, 83.22
2, 34.25, 65.31, 34.75
... etc

I seem to be getting an error around during execution of the function. I would really appreciate some help in fixing this problem.

import csv

Or = csv.reader(open('Or.csv'))
Ne = csv.reader(open('Ne.csv'))

def make_dict(data):
    return OrderedDict((d.split(',',1)[0],d) for d in data if d)
updated = make_dict(Or)
updated.update(make_dict(Ne))

# Write new data to file.csv

Thank-you

3
Contributors
4
Replies
15 Hours
Discussion Span
5 Months Ago
Last Updated
6
Views
Question
Answered
padton
Newbie Poster
14 posts since Sep 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

can you post error details what you are getting so far while running this function?

so that we try to slove your problem

radhakrishna.p
Posting Whiz in Training
263 posts since Nov 2012
Reputation Points: 29
Solved Threads: 59
Skill Endorsements: 10

Thanks radha krishna,

The error is idicated on line 7. AttributeError: 'list' object has no attribute 'split'

padton
Newbie Poster
14 posts since Sep 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

for d in data will give you list objects

Example ...

'''
contents of file or.csv:
1, 23.27, 23.21, 83.22
2, 34.25, 65.31, 34.75
'''

import csv

Or = csv.reader(open('Or.csv'))

for d in Or:
    print(d, type(d))

''' result ...
['1', ' 23.27', ' 23.21', ' 83.22'], <type 'list'>
['2', ' 34.25', ' 65.31', ' 34.75'], <type 'list'>
'''

You have to do something like this ...

'''
contents of file or.csv:
1, 23.27, 23.21, 83.22
2, 34.25, 65.31, 34.75
'''

import csv
import collections as co

def make_dict(data):
    return co.OrderedDict((d[0], d) for d in data if d)

Or = csv.reader(open('Or.csv'))
updated = make_dict(Or)
print(updated)

''' result ...
OrderedDict([('1', ['1', ' 23.27', ' 23.21', ' 83.22']), ('2', ['2', ' 34.25', ' 65.31', ' 34.75'])])
'''
vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 37

Thank-you all for your help.

padton
Newbie Poster
14 posts since Sep 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 5 Months Ago by vegaseat and radhakrishna.p

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0630 seconds using 2.67MB