我在一个列表中迭代字典列表,格式如下(每个字典涉及一件衣服,我只列出了第一件:
new_products = [{'{"uniq_id": "1234", "sku": "abcdefgh", "name": "Levis skinny jeans", '
'"list_price": "75.00", "sale_price": "55.00", "category": "womens"}'}]
def find_product(dictionary, uniqid):
if 'uniq_id' in dictionary:
if ['uniq_id'] == uniqid:
return(keys, values in dictionary)
print(find_product(new_products, '1234'))
这是回归
None
其中出现if
语句的原因是,并非每个产品都有uniq\u id
的值,因此我的代码的早期版本出现了一个关键错误。
你的字典定义很不清楚。
假设你已经给出了一个大小为1的字典列表,它应该是这样的:
new_products = [{"uniq_id": "1234", "sku": "abcdefgh", "name": "Levis skinny jeans", "list_price": "75.00", "sale_price": "55.00", "category": "womens"}]
def find_product(list_of_dicts, uniqid):
for dictionary in list_of_dicts:
if 'uniq_id' in dictionary:
if dictionary['uniq_id'] == uniqid:
return dictionary
print(find_product(new_products, '1234'))