컨텍스트를 설정하려면 변환 된 CSV 출력 파일을 만들기 위해 필자의 요구 사항에 따라 CSV 파일을 변환해야합니다.DictReader 개체를 사용하는 CSV 파일의 사전
나는이 문제점 진술을 위해 파이썬 CSV에서 DictReader
을 사용해야 함을 알게되었습니다. 변환 후 나는 csv 파일에 유지되어야하는 new_point라는 또 다른 사전을 만들려고했다.
문제는 사전을 인쇄 할 때 사전이나 사전의 배열이 아니기 때문에 사전 생성에 코드에 결함이있는 것 같습니다.
with open(out_file, 'w') as f_out, open(in_file, 'r') as f_in:
out_colnames = ['duration', 'month', 'hour', 'day_of_week', 'user_type']
trip_writer = csv.DictWriter(f_out, fieldnames = out_colnames)
trip_writer.writeheader()
trip_reader = csv.DictReader(f_in)
# collect data from and process each row
for row in trip_reader:
# set up a dictionary to hold the values for the cleaned and trimmed
# data point
new_point = {}
## TODO: use the helper functions to get the cleaned data from ##
## the original data dictionaries. ##
## Note that the keys for the new_point dictionary should match ##
## the column names set in the DictWriter object above. ##
duration = duration_in_mins(row, city)
month,hour,day_of_week = time_of_trip(row, city)
user_type = type_of_user(row, city)
new_point['duration'] = duration
new_point['month'] = month
new_point['hour'] = hour
new_point['day_of_week'] = day_of_week
new_point['user_type'] = user_type
pprint(new_point)
나는 내가 아래 점점 오전 new_point의 DICT를 인쇄 할 때 type(new_point)
내가
Class <Dict>
아래와 같은 출력을 얻고 인쇄하는 경우.
{'day_of_week': 'Thursday',
'duration': 7.123116666666666,
'hour': 22,
'month': 3,
'user_type': 'Registered'}
{'day_of_week': 'Thursday',
'duration': 9.792516666666668,
'hour': 22,
'month': 3,
'user_type': 'Registered'}
{'day_of_week': 'Thursday',
'duration': 6.632983333333333,
'hour': 22,
'month': 3,
'user_type': 'Registered'}
{'day_of_week': 'Thursday',
'duration': 7.4047,
'hour': 22,
'month': 3,
'user_type': 'Registered'}
{'day_of_week': 'Thursday',
'duration': 13.014583333333333,
'hour': 22,
'month': 3,
'user_type': 'Registered'}
{'day_of_week': 'Thursday',
'duration': 17.0552,
'hour': 22,
'month': 3,
'user_type': 'Registered'}
{'day_of_week': 'Thursday',
'duration': 11.01165,
'hour': 22,
'month': 3,
'user_type': 'Registered'}
{'day_of_week': 'Thursday',
'duration': 30.01175,
'hour': 21,
'month': 3,
'user_type': 'Registered'}
DictReader 개체에서 사전을 만드는 방법을 이미 따라 한 사람이이 문제를 해결할 수 있습니까?
이 질문을 매우 순진하게 생각한다면 진심으로 사과드립니다. 나는 파이썬에 완전히 새로운 것이다. 나는 문서를 읽으려고했지만 개념을 이해하지 못했습니다. 어디서나 자세한 설명을 찾을 수조차 없습니다.
"사전을 인쇄 할 때 사전이나 사전 배열이 아닙니다."그 설명을 설명해 주시겠습니까? * 출력 된 사전에서 보이는 것처럼 보입니다. – larsks
@larsks 나는 그것에 대해 잘 모르겠다. : 사전처럼 보이지만 for 루프를 사용하여 iterate 할 때 dict의 경우처럼 작동하지 않는다. – dataEnthusiast
'pprint' 라인 바로 다음에'trip_writer.writerow (new_point)'라고 쓰여있는 라인을 삽입하는 것은 어떻습니까? –