字典的Python列表加入列表com

时间:2019-08-12 06:10:48

标签: python-3.x

products = [
    {
        "discontinued": 0,
        "lead_time_days": 4,
        "product_category": "Toy",
        "product_description": "Pull out a bock without crashing the stack ...",
        "product_id": 101,
        "product_name": "Jenga Classic Game",
        "reorder_level": 50,
        "unit_price": 14.99
    },
    {
        "discontinued": 0,
        "lead_time_days": 4,
        "product_category": "Wireless Phone Accessory",
        "product_description": "Display: 2.5 inches Camera: 2 MP Talk Time: 4.5 hours Weight: 3.3 ounces",
        "product_id": 102,
        "product_name": "AT&T Z431 GoPhone (AT&T)",
        "reorder_level": 14,
        "unit_price": 49.99
    },
    {
        "discontinued": 1,
        "lead_time_days": 4,
        "product_category": "Wireless Phone Accessory",
        "product_description": "Display: 4.5-inches Camera: 5-MP Input: Touchscreen OS: Android",
        "product_id": 103,
        "product_name": "AT&T Z998 LTE Android Go Phone (AT&T Prepaid)",
        "reorder_level": 29,
        "unit_price": 159.99
    },
    {
        "discontinued": 1,
        "lead_time_days": 4,
        "product_category": "Personal Computers",
        "product_description": "8 inch Display (1920x1200) ...",
        "product_id": 104,
        "product_name": "NVIDIA SHIELD Tablet (WiFi)",
        "reorder_level": 10,
        "unit_price": 299.0
    }
]

Python词典列表,如何将其product_category及其product_description格式设置为“ product_category-product_description”,例如:product_category-product_description,已终止== 1?

对于格式,请使用join,例如print('- '.join(str1)) 但是我不知道如何链接它们。

1 个答案:

答案 0 :(得分:0)

您可以使用简单的list comprehension(带有if子句来说明discontinued)来遍历列表,并对列表中的每个元素进行join,像这样:

print_messages = [' - '.join([product['product_name'], product['product_description']]) 
                  for product in products if product['discontinued']]

for message in print_messages:
    print(message)