Python字典更新和细化循环

时间:2016-09-01 19:48:24

标签: python dictionary

我正在尝试创建一个循环,在原始传递和解析用户字符串后进一步细化用户定义的字典:

product_info = {'make': [], 'year': [], 'color': []}

make = ['honda','bmw','acura']
year = ['2013','2014','2015','2016']
colors = ['black','grey','red','blue']

user_input = raw_input()

for m in make:
    if m in user_input:
        product_info['make'].append(m)
for y in year:
    if y in user_input:
        product_info['year'].append(y)
for c in color:
    if c in user_input:
        product_info['color'].append(c)

这是我想检查该字典并确保填写所有值的地方,如果没有,请求更多输入以优化现有字典:

示例:I am looking for a grey car

product_info = {'make': [], 'year': [], 'color': ['grey']}

if product_info['make'] is null:
    print 'what make of car are you looking for?'

    new_input = 'i am looking for a 2015 honda'

通过字典/解析过程再次发送字符串,如果有值要填写,请更新product_info字典,并查看这次是否提到了一年等等...

更新了dict:

product_info = {'make': ['honda'], 'year': ['2015'], 'color': ['grey']}

如何接收新用户输入,请求更多信息并解析它,查找属性并更新现有字典而不修改旧属性?

1 个答案:

答案 0 :(得分:1)

while [] in product_info.values():
    for key in product_info:
        if product_info[key] == []:
            print("What",key)
            user_input = raw_input() 
            for each in user_input.split(' '):
                if each in make:
                    key = 'make'
                    product_info[key].append(each)
                elif each in year:
                    key = 'year'
                    product_info[key].append(each)
                elif each in colors:
                    key = 'color'
                    product_info[key].append(each)

这个非常粗糙,有效的系统,你可以改进它,但这取决于你。