[英]How to do list comprehension on a list of dictionaries without returning values in a list?
[英]Why is this dictionary comprehension for list of dictionaries not returning values?
我正在迭代列表中的字典列表,格式如下(每个字典都与一件衣服相关,我只列出了第一个:
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
的值,所以我在早期版本的代码中遇到了关键错误。
你的字典定义很不清楚。
假设你给出了一个大小为 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'))
你正在使用这样的东西:
new_products = [{'{ "some" : "stuff" }'}]
这是一个包含集合( {}
)的列表(外部[]
)
{'{ "some" : "stuff" }'}
注意{1}
是一个包含数字 1 的集合。虽然它使用花括号,但它不是字典。
您的集合包含一个字符串:
'{ "some" : "stuff" }'
如果我询问“some”是否在其中,我会返回True
,但如果我询问此字符串的键,则没有键。
使您的new_products
成为包含字典(而不是集合)的列表,并且不要将有效负载放在字符串中:
new_products = [{"uniq_id": "1234",
"sku": "abcdefgh",
"name": "Levis skinny jeans",
"list_price": "75.00",
"sale_price": "55.00",
"category": "womens"}]
然后遍历 function 列表中的字典:
def find_product(dictionary_list, uniqid):
for d in dictionary_list:
if 'uniq_id' in d:
if d['uniq_id'] == uniqid:
return d.keys(), d.values()
return "not found" # or something better
>>> find_product(new_products, '1234')
(dict_keys(['uniq_id', 'sku', 'name', 'list_price', 'sale_price', 'category']), dict_values(['1234', 'abcdefgh', 'Levis skinny jeans', '75.00', '55.00', 'womens']))
>>> find_product(new_products, '12345')
'not found'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.