Python 字典更新和细化循环

标签 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)

在这里,我想检查该字典并确保所有值都已填充,如果没有,则要求更多输入来完善现有字典:

示例:我正在寻找一辆灰色汽车

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字典(如果有需要填写的值),并查看他们这次是否提到了年份,等等......

更新的字典:

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

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

最佳答案

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)

这个非常粗糙的工作系统,您可以对其进行改进,但这取决于您。

关于Python 字典更新和细化循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39279782/

相关文章:

python - 使用 For 循环修改 Pandas 中的 DataFrame 字典

python - 你如何找到字典中的第一个键?

javascript - 使用 javascript 或 jQuery 使图像映射可选择?

python - 一次寻找 512 字节的模式并打印匹配。

python - Pandas 数据框过滤器计算

python - 如何使用嵌套字典遍历列表?

python - 如何将列追加到字典内的数据框

python - split 对象没有属性点击

python - 初始化多个 Numpy 数组(多重赋值)——类似于 MATLAB deal()

python - 从其他模块访问 python nametuple _fields