从 csv 文件创建字典

Creating dictionary from a csv file

我有一个 csv 文件,如下所示:

EmpID;Day;Duty
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') 的第一天。

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'}
}