Python在循环

时间:2015-09-24 18:01:34

标签: python dictionary

我是编程新手,所以我提前为任何糟糕的代码道歉。这个例子是我的问题的简化版本。我从两个单独的文件中获取数据,这里表示为列表(例如,filea和fileb)。我想要做的是创建一个单词字典(data_dict),其密钥是一个id号;这里是列表中的第一个元素(例如,100)。该值将是一个在更新时附加的列表。在第一个循环(filea)中,id附加到value_list,然后附加一个数据值(对于此示例a9999),然后添加到该键的字典中(id)。

我遇到的问题是试图让第二个循环(fileb)正确追加。最终字典只是第二个循环(fileb)的结果,如b9999所见。从第一个循环中提取键的值,我显然做错了,这样我就可以在第二个循环中添加第二个数据点。我想要实现的最后一本词典是 {100:[100,'a9999','b9999'],101:[100,'a9999','b9999']}没有id开始两次附加到每个列表(例如,[100,'a9999',100, 'b9999'])

filea = [[100,1],[101,1]]
fileb = [[100,2],[101,2]]

def my_func():
    data_dict = {} # a dictionary to hold all data
    for file in [[filea],[fileb]]: 
        name = extra_func(file) #this is only added for the simplified example
        for lists in file: 
            for digit_list in lists:
                value_list = [] # the list that will be the value of each key in data_dict
                id = digit_list[0] #the first item in the list will be the id number
                digit_list.pop(0) #then drop the id number from the list
                data_dict[id] = id #create a key based on the id number 
                #print [data_dict.get(id)] # get the value for that key
                value_list.append(id) #append the id to the value_list
                data = 9999 #this is a placeholder for the example
                value_list.append(name + str(data)) #append the data with name (a or b) for readability
                data_dict[id] = value_list #add the value the key (id)
                #print "data_dict for ", id, data_dict,"\n"
            print "data_dict for all ids in file",name, "\n", data_dict,"\n"
    return data_dict

def extra_func(file):
    if file == [filea]: #this is only added for the simplified example
        name = 'a'
    if file == [fileb]:
        name = 'b'
    return name

data_dict = my_func()
print "final dictionary", data_dict

1 个答案:

答案 0 :(得分:0)

内循环的第一行是问题的开始:你总是从一个新的列表开始。相反,使用dict.get方法获取您想要的起始列表。然后只需添加新数据。

    for lists in file:
        for digit_list in lists:
            # Get the existing list for this ID.
            # If none, start a new one.
            id = digit_list[0] #the first item in the list will be the id number
            value_list = data_dict.get(id, [id])

            digit_list.pop(0) #then drop the id number from the list
            data_dict[id] = id #create a key based on the id number 
            #print [data_dict.get(id)] # get the value for that key
            data = 9999 #this is a placeholder for the example
            value_list.append(name + str(data)) #append the data with name (a or b) for readability
            data_dict[id] = value_list #add the value the key (id)
            #print "data_dict for ", id, data_dict,"\n"
        print "data_dict for all ids in file",name, "\n", data_dict,"\n"