2017-09-23 102 views
-2

我有一个列表,我需要过滤该列表并获得一些关键值。这是列表:如何筛选python列表?

"products":[ 
     { 
     "discount":"0.00000", 
     "id":"6f47e339-34a0-8c58-11e7-9f96677d9fcc", 
     "loyalty_value":"0.00000", 
     "price":"0.00000", 
     "price_set":false, 
     "price_total":"0.00000", 
     "product_id":"0af7b240-ab09-11e7-eddc-8cb82351211c", 
     "quantity":1, 
     }, 
     { 
     "discount":"0.00000", 
     "id":"6f47e339-34a0-8c58-11e7-9f966ecf8e5f", 
     "loyalty_value":"0.00000", 
     "price":"3.18182", 
     "price_set":false, 
     "price_total":"3.18182", 
     "product_id":"0af7b240-ab09-11e7-eddc-80d691bbf094", 
     "quantity":1, 
     }, 
     { 
     "discount":"0.00000", 
     "id":"6f47e339-34a0-8c58-11e7-9f96701777b2", 
     "loyalty_value":"0.00000", 
     "price":"2.72727", 
     "price_set":false, 
     "price_total":"2.72727", 
     "product_id":"0af7b240-ab09-11e7-eddc-80a522346b58", 
     "quantity":1, 
     } 

    ] 

我需要像过滤后从上面列表中得到相同的列表:

"LstProduct": [ 
    { 
     "product_id": "string", 
     "price": 0, 
     "quantity": 0 
    }, 
    { 
     "product_id": "string", 
     "price": 0, 
     "quantity": 0 
    }, 
    { 
     "product_id": "string", 
     "price": 0, 
     "quantity": 0 
    } 
    ] 

回答

2

您可以创建具有您需要为您的新列表中的键一个新的列表。然后,你可以使用过滤列表理解作为结果:

filtered_keys = ["product_id", "price", "quantity"] 

new_list = [{key: element[key] for key in filtered_keys} for element in old_list] 

其中old_list是你的字典对象列表。

+0

非常感谢。它为我工作。 –

+0

乐意帮忙@NitinSherawat。如果您发现任何对您的问题有用的答案,您应该将[最佳答案标记为已接受](https://meta.stackexchange.com/questions/23138/how-to-accept-the-answer-on-stack -溢出)。有关详细信息,请检查:[如何接受答案工作?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) –

+0

我建议修改现有的列表而不是创建新的 –