Python在循环中更新字典中的键和值

2024-09-29 19:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我遇到的问题是试图让第二个循环(fileb)正确附加。最终的字典只是第二个循环(fileb)的结果,正如b9999所看到的那样。从第一个循环中提取键的值,这样我就可以在第二个循环中添加第二个数据点,这显然是做错了。我要做的最后一本字典是 {100:[100,'a9999','b9999',101:[100,'a9999','b9999']}不带id的begin附加到每个列表两次(例如,[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

Tags: thenameinid列表fordata字典
1条回答
网友
1楼 · 发布于 2024-09-29 19:21:51

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

    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"

相关问题 更多 >

    热门问题