【问题标题】:Picking Values from a List to Update Dictionary从列表中选取值以更新字典
【发布时间】:2016-07-18 13:46:00
【问题描述】:

我的场景是这样的:

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'}..]

【问题讨论】:

标签: python dictionary


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2022-08-12
    • 2022-01-16
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    相关资源
    最近更新 更多