[英]Why is this dictionary comprehension for list of dictionaries not returning values?
I am iterating over a list of dictionaries in a list formatted as follows (each dictionary relates to one item of clothing, I have only listed the first:我正在迭代列表中的字典列表,格式如下(每个字典都与一件衣服相关,我只列出了第一个:
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'))
This is returning这是回归
None
The reason for the if
statement in there is that not every product has a value for uniq_id
so I was getting a key error on an earlier version of my code. if
语句的原因是不是每个产品都有uniq_id
的值,所以我在早期版本的代码中遇到了关键错误。
Your dictionary definition is quite unclear.你的字典定义很不清楚。
Assuming that you have given a list of dictionaries of size 1, it should be something like this:假设你给出了一个大小为 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'))
You are using something like this:你正在使用这样的东西:
new_products = [{'{ "some" : "stuff" }'}]
This is a list (the outer []
) containing a set (the {}
)这是一个包含集合(
{}
)的列表(外部[]
)
{'{ "some" : "stuff" }'}
Note {1}
is a set containing the number 1. Though it uses the curly braces it isn't a dictionary.注意
{1}
是一个包含数字 1 的集合。虽然它使用花括号,但它不是字典。
Your set contains a string:您的集合包含一个字符串:
'{ "some" : "stuff" }'
If I ask if 'some' is in this, I get True
back, but if I ask for this string's keys there are no keys.如果我询问“some”是否在其中,我会返回
True
,但如果我询问此字符串的键,则没有键。
Make your new_products
a list containing a dictionary (not a set), and don't put the payload in a string:使您的
new_products
成为包含字典(而不是集合)的列表,并且不要将有效负载放在字符串中:
new_products = [{"uniq_id": "1234",
"sku": "abcdefgh",
"name": "Levis skinny jeans",
"list_price": "75.00",
"sale_price": "55.00",
"category": "womens"}]
Then loop over the dictionaries in the list in your function:然后遍历 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.