【发布时间】:2011-11-06 23:28:40
【问题描述】:
我正在使用 os.listdir 和一个文件来创建字典。我分别从它们那里获取键和值。
os.listdir 给我:
EVENT3180
EVENT2894
EVENT2996
从我得到的文件中:
3.1253 -32.8828 138.2464
11.2087 -33.2371 138.3230
15.8663 -33.1403 138.3051
主要问题是我的最终字典有不同的键但总是相同的值,这不是我想要的。我想要得到的是:
{'EVENT3180': 3.1253 -32.8828 138.2464, 'EVENT2894': 11.2087 -33.2371 138.3230, 'EVENT2996': 15.8663 -33.1403 138.3051}
所以我认为我的代码循环遍历键而不是值。无论如何,到目前为止我的代码:
def reloc_event_coords_dic ():
event_list = os.listdir('/Users/working_directory/observed_arrivals_loc3d')
adict = {}
os.chdir(path) # declared somewhere else
with open ('reloc_coord_complete', 'r') as coords_file:
for line in coords_file:
line = line.strip() #Gives me the values
for name in event_list: # name is the key
entry = adict.get (name, [])
entry.append (line)
adict [name] = entry
return adict
感谢阅读!
【问题讨论】:
标签: python file dictionary for-loop