在python中将文件读入字典,如何确保没有重复?

时间:2016-09-30 19:34:42

标签: python-3.x dictionary text-files

我正在读取文件并在每行中创建前两个项目的字典,如何确保没有任何键是相同的,以便在发生这种情况时我可以关闭文件?我有制作字典的代码,但我不确定如何进行此故障排除,任何见解都会非常感激!: 这是我的字典代码:

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

1 个答案:

答案 0 :(得分: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