我正在使用python 3,我的目标是读取.csv文件并将其仅打印为dictionary(json)格式的第一行,也按键排序。我付出了很多努力并需要帮助。我所尝试的一切如下:-
def list_of_csvs(csvfile):
with open(csvfile, mode = 'r') as csvFile:
reader = csv.DictReader(csvFile)
for row in reader:
return row
row = list_of_csvs('NYC-CitiBike-2016.csv')
print(dict(row))
尽管它仍然没有按键排序。请提出最佳方法。
输出应如下所示(请参阅排序的键和对齐方式)
City: NYC
{'bikeid': '17109',
'birth year': '',
'end station id': '401',
'end station latitude': '40.72019576',
'end station longitude': '-73.98997825',
'end station name': 'Allen St & Rivington St',
'gender': '0',
'start station id': '532',
'start station latitude': '40.710451',
'start station longitude': '-73.960876',
'start station name': 'S 5 Pl & S 4 St',
'starttime': '1/1/2016 00:09:55',
'stoptime': '1/1/2016 00:23:54',
'tripduration': '839',
'usertype': 'Customer'}
答案 0 :(得分:0)
要对字典进行排序,请尝试如下操作:
print({k: mydict[k] for k in sorted(mydict)})