I'm trying to iterate a list of dictionaries with a for
loop in this way:
my_list = []
while True:
print("Welcome, choose number 1")
print("1.- Coke")
numb = input()
if numb is "1":
for l in my_list:
if l["product"] is "coke":
l["count"] += 1
else:
Coke = {"product":"coke", "count":1, "price":17.5}
my_list.append(Coke)
What I expect the code to do is to search in each dictionary inside the list to find a match and add 1 to count
value or in case such dictionary don't exist to create it and append it, but when running the code it just keeps my_list
empty.
I've tried to delete the iteration and go directly to the creation of the dict which it does without a problem, but when doing the iteration I got no result.
使用 list_name[list_index][dict_key] 访问字典列表中字典中的值,前提是列表索引和字典键已知
The problem with your code is
Initially, my_list is empty so the for loop is not executing at all.So your final result will be always an empty list. Try including a single element in the my_list
my_list = [{"product":"coke", "count":1, "price":17.5}]
while True:
print("Welcome, choose number 1")
print("1.- Coke")
numb = input()
if numb is "1":
for l in my_list:
if l["product"] is "coke":
l["count"] += 1
else:
Coke = {"product":"coke", "count":1, "price":17.5}
my_list.append(Coke)
Try this will solve your problem.
First of all, in Python we use ==
to compare with a literal, and if you use is
, Python will give a SyntaxWarning
. Second, in your code, if my_list
is empty, then the code after for l in my_list
won't be executed because it won't iterate over anything. So the code can be:
my_list = []
while True:
print("Welcome, choose number 1")
print("1.- Coke")
numb = input()
if numb == "1":
for l in my_list:
if l["product"] == "coke":
l["count"] += 1
break
else:
Coke = {"product": "coke", "count": 1, "price": 17.5}
my_list.append(Coke)
Where the else
after the for
means "if the for
exited without a break
".
Hope it helps you ;-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.