【发布时间】:2022-01-23 19:33:30
【问题描述】:
我正在迭代列表中的字典列表,格式如下(每个字典都与一件衣服相关,我只列出了第一个:
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_id 的值,所以我在早期版本的代码中遇到了关键错误。
【问题讨论】:
-
问题是带有
"uniq_id"的字典是new_products列表中字典的字符串表示,而不是实际的字典对象——所以它从未被你的if。 -
但是 print(type(reviewers_dicts[1])) 返回 dict。
-
不知道
reviewers_dicts是什么。从您的问题中显示的内容来看:type(new_products[0])→<class 'set'>,并且字典的字符串表示形式是set的成员,它是new_products列表的第一个(也是唯一一个)元素。你的数据结构搞砸了。
标签: python dictionary-comprehension