Reputation: 23
I have python code to parse out a CSV as follows
def process_incoming_file(self, bucket, key, event):
try:
line_count = 0
timestamp = 0
print('processing data')
response = self.client.get_object(Bucket=bucket, Key=key)
decoded_content = response['Body'].read().decode('utf-8')
print(decoded_content)
reader = csv.reader(decoded_content.splitlines(), delimiter=',')
rows = list(reader)
for row in rows:
fid = uuid.uuid4()
if line_count == 0:
keys = row
print('keys', keys)
line_count += 1
else:
inProj = Proj(init='epsg:27700') #British National Grid
outProj = Proj(init='epsg:4326') #WGS84
x1, y1 = row[1], row[2] # easting, northing
x2, y2 = transform(inProj, outProj, x1, y1)
row[1], row[2] = y2, x2
json_doc = {}
for idx,el in enumerate(row):
if keys[idx].lower() in ['time', 'date serviced']:
timestamp = self.format_timestring(row[idx])
else:
json_doc[keys[idx]] = row[idx]
print(row[0])
print (fid)
print(timestamp)
print(json_doc)
line_count += 1
except Exception as e:
print(e)
return
The above codes then return my results as:
108
df44d8ef-1ace-40cb-9cb6-ebbce0bb78ed
1579219200
{'Object': '108', 'Easting': 50.15466792673487, 'Northing': -5.066927538249519}
However, I would like to update the key names from 'Easting' to 'Latitude', and 'Northing' to 'Longitude', like this:
108
df44d8ef-1ace-40cb-9cb6-ebbce0bb78ed
1579219200
{'Object': '108', 'Latitude': 50.15466792673487, 'Longitude': -5.066927538249519}
Does anyone know how to do it?
Upvotes: 1
Views: 73
Reputation: 5637
From the codes, json_doc
looks like a dictionary. We could change the keys using
dictionary[new_key] = dictionary.pop(old_key)
Do some processing before printing the results:
json_doc = {'Object': '108', 'Easting': 50.15466792673487, 'Northing': -5.066927538249519}
json_doc['Latitude'] = json_doc.pop('Easting')
json_doc['Longitude'] = json_doc.pop('Northing')
print(json_doc)
Output
{'Object': '108', 'Latitude': 50.15466792673487, 'Longitude': -5.066927538249519}
Upvotes: 2
Reputation: 54168
Write the copy and the deletion of the old keys
json_doc['Latitude'] = json_doc['Easting']
del json_doc['Easting']
json_doc['Longitude'] = json_doc['Northing']
del json_doc['Northing']
Upvotes: 1