[英]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.