在一个小型python项目上工作,并且达到了令我难过的地步。
runners = ["Tom","Bob","Bill","Gary"]
runner_id = [123223,234345,356543,487334]
event_id = [11,12,13,14]
event_time = [12.30,13.00,14.00,16.00]
我有上面的数据,希望最终得到每个跑步者的字典,并将dict命名为跑步者名称。
结果如下:
Tom = {runner_id : 123223, event_id : 11, event_time : 12.30}
Bob = {runner_id : 234345, event_id : 12, event_time : 13.00}
Bill = {runner_id : 356543, event_id : 13, event_time : 14.00}
Gary = {runner_id : 487334, event_id : 14, event_time : 16.00}
难以理解如何将dict命名为我需要它,即作为原始列表之一的名称。
已阅读了大量帖子,但无法找到此特定问题的答案。
感谢所有有用的指示。
非常感谢。
答案 0 :(得分:3)
您可以使用词典理解和zip
功能:
runners = ["Tom","Bob","Bill","Gary"]
runner_id = [123223,234345,356543,487334]
event_id = [11,12,13,14]
event_time = [12.30,13.00,14.00,16.00]
print {name:{'runner_id' : i, 'event_id' : j, 'event_time' : k} for i,j,k,name in zip(runner_id,event_id,event_time,runners)}
结果:
{'Bob': {'event_id': 12, 'event_time': 13.0, 'runner_id': 234345}, 'Bill': {'event_id': 13, 'event_time': 14.0, 'runner_id': 356543}, 'Gary': {'event_id': 14, 'event_time': 16.0, 'runner_id': 487334}, 'Tom': {'event_id': 11, 'event_time': 12.3, 'runner_id': 123223}}
[Finished in 0.1s]
答案 1 :(得分:1)
您必须使用跑步者名称作为较大词典的键
runner_dict = {}
for index, runner in enumerate(runners):
runner_dict[runner] = {
'runner_id' : runner_id[index],
'event_id' : event_id[index],
'event_time' : event_time[index]
}
答案 2 :(得分:0)
如果您有一个包含所有跑步者及其词典的字典,那就好多了。所以相反,你有这个:
runners = {
"Tom" : {runner_id : 123223, event_id : 11, event_time : 12.30},
"Bob" : {runner_id : 234345, event_id : 12, event_time : 13.00},
"Bill" : {runner_id : 356543, event_id : 13, event_time : 14.00},
"Gary" : {runner_id : 487334, event_id : 14, event_time : 16.00},
}
答案 3 :(得分:0)
如下
runners = ["Tom","Bob","Bill","Gary"]
runner_id = [123223,234345,356543,487334]
event_id = [11,12,13,14]
event_time = [12.30,13.00,14.00,16.00]
runners_dict = {}
for index, runner in enumerate(runners):
runners_dict[runner] = {
'runner_id' : runner_id[index],
'event_id' : event_id[index],
'event_time' : event_time[index]
}
如果你想得到某些跑步者的话,那么
runners_dict['name']