我有这个功能可以在字典中进行更改。
a_dict = {"car": ["audi"],
"company": ["apple"]}
def add_dict(vehicle,brand,stuff):
for keyword in stuff:
if keyword == vehicle:
if brand not in stuff[keyword]:
stuff[keyword].append(brand)
break
else:
stuff[vehicle] = [brand]
break
add_dict("car","bmw",a_dict)
print(a_dict)
此代码会将“bmw”添加到键“car”。但是,当我再次运行代码时,例如使用“mercedes”而不是 bmw,它将字典重置为第一个。我希望它继续添加更新的列表。
现在,else
如果至少有一个不匹配的键,则该子句会触发vehicle
。像这样修复它:
def add_to_dict(product_type, brand, product_dict):
if product_type in product_dict:
product_dict[product_type].append(brand)
else:
product_dict[product_type] = [brand]
product_dict = {}
add_to_dict("car", "audi", product_dict)
add_to_dict("car", "mercedes", product_dict)
add_to_dict("phone", "apple", product_dict)
print(product_dict)
# Output:
# {"car": ["audi","mercedes"], "phone": ["apple"]}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句