user25976 user25976 - 24 days ago 5
Python Question

Formatting different types of data in CSV columns using Python

I'm writing multiple dictionaries to a csv file using Python. The first column is an column with IDS, the next several are float data formatted to a precision of two decimal places, and the last is string data. I'm a beginner, so this error message is throwing me for a loop.

print TotalData
({0.0: 7194.9500000000035, 1.0: 2456.1200000000003, 2.0: 2333.0699999999997, 3.0: 1645.37}, {0.0: 27400.0, 1.0: 32900.0, 2.0: 42200.0, 3.0: 40600.0}, {0.0: 33, 1.0: 35, 2.0: 35, 3.0: 42}, {0.0: 1800.0, 1.0: 1900.0, 2.0: 1900.0, 3.0: 1800.0}, {0.0: 800.0, 1.0: 500.0, 2.0: 400.0, 3.0: 500.0}, {0.0: 830.30303030303025, 1.0: 940.0, 2.0: 1205.7142857142858, 3.0: 966.66666666666663}, {0.0: 101.48148148148148, 1.0: 82.25, 2.0: 136.1290322580645, 3.0: 101.49999999999999}, {0.0: -400.0, 1.0: 7100.0, 2.0: -11200.0, 3.0: -600.0}, {0.0: -0.014598540145985401, 1.0: 0.21580547112462006, 2.0: -0.26540284360189575, 3.0: -0.014778325123152709}, {0.0: 'POINT(254123,8.03835e+06)', 1.0: 'POINT(254603,8.03829e+06)', 2.0: 'POINT(254905,8.03863e+06)', 3.0: 'POINT(254606,8.03871e+06)'})


Those are my dictionaries.

TotalData = LongCanal, ConsoSom, ConsoCompte, ConsoMax, ConsoMin, ConsoMoyn, Rendement, vFuites, ILP, XYcoord
ListData = list(TotalData)

with open('AEP_data.csv', 'wb') as ofile:
writer = csv.writer(ofile, quoting=csv.QUOTE_NONE, delimiter='\t')
writer.writerow(['FID_CG', 'LongCanal', 'ConsoSom', 'ConsoCompte', 'ConsoMax', 'ConsoMin', 'ConsoMoyn', 'Rendement', 'vFuites', 'ILP', 'XYcoord'])
for key in sorted(LongCanal.iterkeys(), key=lambda x: int(x)):
writer.writerow([key] + ['{0:.2f}'.format(d[key]) for d in TotalData[0:8]] + [d[key] for d in TotalData[9]])



TypeError: 'float' object has no attribute '__getitem__'


When I remove the string dictionary, and format all float values to '{0:.2f}' everything works fine.

Any help would be appreciated. Mahalo in advance.

Answer

The error message is saying that one of the things you THINK is a dictionary, is actually just a float. If we try to print the last part of your writer statement:

print [d[key] for d in TotalData[9]]

We get this same error as above:

TypeError: 'float' object has no attribute '__getitem__'

So we have identified the source of the problem.

I can not quite tell what you are trying to do, but your key parameter exactly matches the values of d in this last list comprehension. Because of that, I am going to go ahead and guess this is what you want:

for key in sorted(LongCanal.iterkeys(), key=lambda x: int(x)):
    writer.writerow([key] + ['{0:.2f}'.format(d[key]) for d in TotalData[0:8]] + [TotalData[9][key]])
Comments