2016-09-30 45 views
-2

我正在阅读一个文件,并在每行中创建前两项的字典,我如何确保没有任何键是相同的,以便在这种情况下可以关闭文件?我有一个做了字典中的代码,但我不确定如何做到这一点的故障排除,任何见解将不胜感激!: 这里是我的字典代码:在Python中将文件读入字典中,如何确保没有重复项?

my_dict = {} 
info = open(data_file,"r") 
for line in info: 
    line = line.rstrip() 
    items = line.split('\t') 
    ID = items[0] 
    Value = items[1] 
    my_dict[ID] = Value 
    return my_dict 
+0

你的意思只是检查'如果ID在my_dict:'? – AChampion

+0

是的,因为它是输入到字典中的项目,我希望它停止,如果有和重复的ID – fuk

+0

只需检查'如果在my_dict中的ID:在行'my_dict [ID] =值' – AChampion

回答

0

就像这样:

my_dict = {} 
with open(data_file,"r") as info: # Closes upon finishing 
    for line in info: 
     items = line.rstrip().split('\t') 
     ID = items[0] 
     Value = items[1] 
     if ID in my_dict: # Exits the for loop if ID already exists 
      break 
     my_dict[ID] = Value 

    return my_dict # Returns the gathered data 
相关问题