我有一個 csv 檔案,如下所示:
EmpID ; 天; 關稅
521;0;1
521;1;1
521;2;0
521;3;0
521;4;1
521;5;1
521;6;??0
521;7;0
521;8;1
521;9; 1
521;10;0
521;11;0
521;12;1
521;13;1
879;0;1
879;1;0
879;2;1
879;3;0
879;4;1
879;5; 0
879;6;1
879;7;0
879;8;1
879;9;0
879;10;1
879;11;0
879;12;1
879;13;1
978;0;1
978;1; 1
978;2;0
978;3;1
978;4;1
978;5;1
978;6;0
978;7;1
978;8;1
978;9;1
978;10;1
978;11;1
978;12;0
978;13;1
979;0;1
979;1;1
979;2;1
979;3;0
979;4;1
979;5;1
979;6;1
979;7;0
979;8;1
979;9;1
979;10;1
979;11;1
979;12;0
979;13;1 \
第一個數字表示員工的ID,然后是作業時間表的日期,最后一個數字表示該員工當天是否作業。
0:員工當天不
作業
1:員工當天作業
我想撰寫一個以EmpID作為鍵,以另一個字典作為值的字典。內部字典應包含Day作為鍵和Duty作為值。
所以這就是我所擁有的:
def schedule_dict(file):
the_dict = csv.DictReader(file, delimiter = ';')
schedule={}
for item in the_dict:
schedule[item['EmpID']] = {}
for thing in the_dict:
schedule[item['EmpID']].update({thing['Day'] : thing['Duty']})
if int(thing['Day']) == 13:
break
return schedule
我已經使用DictReader命令閱讀了 csv 檔案,并得到了這本字典:
{
'521': {'1': '1', '2': '0', '3': '0', '4': '1', '5': '1', '6': '0', '7': '0', '8': '1', '9': '1', '10': '0', '11': '0', '12': '1', '13': '1'},
'879': {'1': '0', '2': '1', '3': '0', '4': '1', '5': '0', '6': '1', '7': '0', '8': '1', '9': '0', '10': '1', '11': '0', '12': '1', '13': '1'},
'978': {'1': '1', '2': '0', '3': '1', '4': '1', '5': '1', '6': '0', '7': '1', '8': '1', '9': '1', '10': '1', '11': '1', '12': '0', '13': '1'},
'979': {'1': '1', '2': '1', '3': '0', '4': '1', '5': '1', '6': '1', '7': '0', '8': '1', '9': '1', '10': '1', '11': '1', '12': '0', '13': '1'}
}
但我仍然需要數字為零('0')的第一天。
uj5u.com熱心網友回復:
with open("your_file.csv", "r") as f:
the_dict = list(map(lambda y: y.split(";"), [line.strip() for line in f]))
schedule = {}
for item in the_dict:
if item[0] not in schedule.keys():
schedule.setdefault(item[0], {item[1]: item[2]})
else:
schedule[item[0]].update({item[1]: item[2]})
print(schedule)
{
'521': {'0': '1', '1': '1', '2': '0', '3': '0', '4': '1', '5': '1', '6': '0', '7': '0', '8': '1', '9': '1', '10': '0', '11': '0', '12': '1', '13': '1'}
'879': {'0': '1', '1': '0', '2': '1', '3': '0', '4': '1', '5': '0', '6': '1', '7': '0', '8': '1', '9': '0', '10': '1', '11': '0', '12': '1', '13': '1'}
'978': {'0': '1', '1': '1', '2': '0', '3': '1', '4': '1', '5': '1', '6': '0', '7': '1', '8': '1', '9': '1', '10': '1', '11': '1', '12': '0', '13': '1'}
'979': {'0': '1', '1': '1', '2': '1', '3': '0', '4': '1', '5': '1', '6': '1', '7': '0', '8': '1', '9': '1', '10': '1', '11': '1', '12': '0', '13': '1'}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/441443.html
