从列表中选择值以更新字典

时间:2016-07-18 13:46:01

标签: python dictionary

我的情况是这样的:

pic_from_list = ['best', 'good', 'ok']
dict_list = [{id = "1", food_source : "this food;is;good"}, {id = "2", food_source : "this food;is;ok"}, {id = "3", food_source : "this food is the best"}, {id = "4", food_source : none}, {id = "5", food_source : "no source"}]

我的代码是这样的:

for item in dict_list:
    idt = item['id']
    #print(idt)

    source = item['source']
    #print(source)
    words = re.split(r'[.|;]+', str(source))
    #print(words)
    class_type = [i.strip() for i in words if i in pic_from_list]
    #print(class_type)

    if len(class_type) ==0:
        if idt not in new_dict.values():
            new_dict.update({'id': idt , 'food_class': 'none'})

            dict_list.append(new_dict)
        else:
            pass
    elif:
if idt not in new_dict.values():
            new_dict.update({'id': idt , 'food_class': 'none'})

            dict_list.append(new_dict)
        else:
            pass
print(dict_list[:4])

给了我错误的输入,如:

[{'id':1, food_class:'none'}, {'id':1, food_class:'good'}, {'id':1, food_class:'ok'}..]

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。显然,我在循环之外定义字典!所以每次,代码都会生成一个循环,字典被覆盖而密钥没有变化,只有值。当我在循环中定义字典时,它会重新开始作为空字典,然后将键和值对添加到字典中。