我有一个如下所示的CSV文件:
Martin;Sailor;-0.24
Joseph_4;Sailor;-0.12
Alex;Teacher;-0.23
Maria;Teacher;-0.57
我的目标是为每个作业创建一个包含词典的列表。
例如:
list_of_jobs = [{'Job' : Sailor, 'People' : ['Martin', 'Joseph']}
{'Job' : Teacher, 'People' : ['Alex', 'Maria']}
]
我确实创建了词典,但我无法弄清楚如何更新list_of_jobs['People']
有人能帮助我吗?
答案 0 :(得分:0)
job_dict={}
job_dict['Sailor']=['Martin','Joseph']
job_dict['Teacher']=['Alex','Maria']
如果您想将“Marcos”添加为水手,您可以:
(job_dict['Sailor']).append('Marcos')
答案 1 :(得分:0)
您的数据结构不适合这项工作;考虑使用另一个,然后在最后改为你的:
data = "Martin;Sailor;-0.24 Joseph_4;Sailor;-0.12 Alex;Teacher;-0.23 Maria;Teacher;-0.57"
data = [r.split()[-1] for r in data.split(';')]
# data = ['Martin', 'Sailor', 'Joseph_4', 'Sailor', 'Alex', 'Teacher', 'Maria', 'Teacher', '-0.57']
# for the moment use one dict keyed with jobs for easy updating
out = {}
for name, job in zip(data[::2], data[1::2]):
out.setdefault(job, []).append(name)
# out = {'Sailor': ['Martin', 'Joseph_4'], 'Teacher': ['Alex', 'Maria']}
# in the very end, convert to desired output format
out = [{'Job': job, 'People': people} for job, people in out.items()]
# out = [{'Job': 'Sailor', 'People': ['Martin', 'Joseph_4']}, {'Job': 'Teacher', 'People': ['Alex', 'Maria']}]
答案 2 :(得分:0)
如果你有这样的字典列表:
Test Measure
您可以按索引访问字典。
list_of_jobs = [
{'Job' : 'Sailor', 'People' : ['Martin', 'Joseph']},
{'Job' : 'Teacher', 'People' : ['Alex', 'Maria']}
]
如果要访问第一个字典的“People”属性,可以这样做:
list_of_jobs[0]
Output:
{'Job' : 'Sailor', 'People' : ['Martin', 'Joseph']}
如果要修改该人员列表的值,可以使用append()添加项目,或使用pop()从列表中删除项目。
list_of_jobs[0]['People']
Output:
['Martin', 'Joseph']
现在,list_of_jobs将具有以下状态:
list_of_jobs[0]['People'].append('Andrew')
list_of_jobs[0]['People'].pop(1)