Python 3.x Python将dict内容添加到dict列表中

Python 3.x Python将dict内容添加到dict列表中,python-3.x,Python 3.x,我以JSON的形式接收订单,其中多个订单项作为列表添加,如下所示: 订单样本 我需要将这些JSON订单“转换”为CSV,在CSV中为每个订单项创建一个新行。上面的示例将生成一个包含两行的CSV。当以“手动”方式添加所有数据时,这可以很好地工作——这意味着添加地址数据,如“recipientCompany”:订单有效载荷[“addressData”][“recipientCompany”] 我想做的是添加整个字典order\u payload[“addressData”]w/o手动添加每个字段 我

我以JSON的形式接收订单,其中多个订单项作为列表添加,如下所示:

订单样本

我需要将这些JSON订单“转换”为CSV,在CSV中为每个订单项创建一个新行。上面的示例将生成一个包含两行的CSV。当以“手动”方式添加所有数据时,这可以很好地工作——这意味着添加地址数据,如
“recipientCompany”:订单有效载荷[“addressData”][“recipientCompany”]

我想做的是添加整个字典
order\u payload[“addressData”]
w/o手动添加每个字段

我尝试过使用
extend
,但我只将键添加到dict中,我不知道如何在我的
orders.append()中列出/dict理解

我已经尝试使用以下方法添加键值对

(key: value for (key, value) in order_payload["externalReferences"])
但这也不起作用

我相信有一个(非常)简单的方法,但我没有找到一个在这方面对我有帮助的答案

# order_payload is just a 'json.loads' of the above order
def main(order_payload):
    orders = []
    for order_item in order_payload["orderItem"]:
        orders.append({
            "orderDate": order_payload["importDate"],
            "sku": order_item["sku"],
            "itemName": order_item["itemName"]
            # TODO dynamically add contents of order_payload["addressData"]
        })

提前感谢

您可以简单地将dict与
地址数据
子dict合并。这说明了如何执行dict合并

代码

for order_item in order_payload["orderItem"]:
    new_dict = {
        **{
            "orderDate": order_payload["importDate"],
            "sku": order_item["sku"],
            "itemName": order_item["itemName"]
            # TODO dynamically add contents of order_payload["addressData"]
        }, 
        **order_payload["addressData"]
    }
    orders.append(new_dict)
如果希望输出内联:

orders_2 = [{**{k: v for k, v in data.items() if k not in ["addressData", "orderItem"]},
             **data["addressData"], ** order_item} for order_item in data["orderItem"]]

完整代码

data = {
    "importDate": "2020-03-18T10:03:19.194336",
    "status": "shipped",
    "orderNumber": 123456,
    "orderItem": [
        {
            "sku": 998877,
            "itemName": "Doomsday device",
            "netCost": 8.7,
            "quantity": 1
        },
        {
            "sku": 665544,
            "itemName": "Fing longerer",
            "netCost": 99.9,
            "quantity": 1
        }
    ],
    "addressData": {
        "recipientCompany": "Planet Express, Inc",
        "recipientName": "Farnsworth",
        "recipientFirstName": "Hubert",
        "recipientStreet": "72nd Street",
        "recipientHouseNumber": None,
        "recipientAnnex": None,
        "recipientZip": "NNY 10023",
        "recipientCity": "New New York",
        "recipientCountry": "USA",
        "recipientEmail": "hubert@farnsworth.com",
        "recipientPhone": "+123 445-566-7789",
        "recipientMobilePhone": "+123 444 555 666 777"
    }
}

def main(order_payload):
    orders = []
    for order_item in order_payload["orderItem"]:
        new_dict = {
            **{
                "orderDate": order_payload["importDate"],
                "sku": order_item["sku"],
                "itemName": order_item["itemName"]
            }, 
            **order_payload["addressData"]
        }
        orders.append(new_dict)
    return orders

orders_1 = main(data)
orders_2 = [{**{k: v for k, v in data.items() if k not in ["addressData", "orderItem"]},
             **order_item, **data["addressData"]} for order_item in data["orderItem"]]

print(orders_1)
# [
#     {
#         "orderDate": "2020-03-18T10:03:19.194336",
#         "sku": 998877,
#         "itemName": "Doomsday device",
#         "recipientCompany": "Planet Express, Inc",
#         "recipientName": "Farnsworth",
#         "recipientFirstName": "Hubert",
#         "recipientStreet": "72nd Street",
#         "recipientHouseNumber": null,
#         "recipientAnnex": null,
#         "recipientZip": "NNY 10023",
#         "recipientCity": "New New York",
#         "recipientCountry": "USA",
#         "recipientEmail": "hubert@farnsworth.com",
#         "recipientPhone": "+123 445-566-7789",
#         "recipientMobilePhone": "+123 444 555 666 777"
#     },
#     {
#         "orderDate": "2020-03-18T10:03:19.194336",
#         "sku": 665544,
#         "itemName": "Fing longerer",
#         "recipientCompany": "Planet Express, Inc",
#         "recipientName": "Farnsworth",
#         "recipientFirstName": "Hubert",
#         "recipientStreet": "72nd Street",
#         "recipientHouseNumber": null,
#         "recipientAnnex": null,
#         "recipientZip": "NNY 10023",
#         "recipientCity": "New New York",
#         "recipientCountry": "USA",
#         "recipientEmail": "hubert@farnsworth.com",
#         "recipientPhone": "+123 445-566-7789",
#         "recipientMobilePhone": "+123 444 555 666 777"
#     }
# ]
print(orders_2)
# [
#     {
#         "importDate": "2020-03-18T10:03:19.194336",
#         "status": "shipped",
#         "orderNumber": 123456,
#         "sku": 998877,
#         "itemName": "Doomsday device",
#         "netCost": 8.7,
#         "quantity": 1,
#         "recipientCompany": "Planet Express, Inc",
#         "recipientName": "Farnsworth",
#         "recipientFirstName": "Hubert",
#         "recipientStreet": "72nd Street",
#         "recipientHouseNumber": null,
#         "recipientAnnex": null,
#         "recipientZip": "NNY 10023",
#         "recipientCity": "New New York",
#         "recipientCountry": "USA",
#         "recipientEmail": "hubert@farnsworth.com",
#         "recipientPhone": "+123 445-566-7789",
#         "recipientMobilePhone": "+123 444 555 666 777"
#     },
#     {
#         "importDate": "2020-03-18T10:03:19.194336",
#         "status": "shipped",
#         "orderNumber": 123456,
#         "sku": 665544,
#         "itemName": "Fing longerer",
#         "netCost": 99.9,
#         "quantity": 1,
#         "recipientCompany": "Planet Express, Inc",
#         "recipientName": "Farnsworth",
#         "recipientFirstName": "Hubert",
#         "recipientStreet": "72nd Street",
#         "recipientHouseNumber": null,
#         "recipientAnnex": null,
#         "recipientZip": "NNY 10023",
#         "recipientCity": "New New York",
#         "recipientCountry": "USA",
#         "recipientEmail": "hubert@farnsworth.com",
#         "recipientPhone": "+123 445-566-7789",
#         "recipientMobilePhone": "+123 444 555 666 777"
#     }
# ]

您只需将dict与
addressData
子dict合并即可。这说明了如何执行dict合并

代码

for order_item in order_payload["orderItem"]:
    new_dict = {
        **{
            "orderDate": order_payload["importDate"],
            "sku": order_item["sku"],
            "itemName": order_item["itemName"]
            # TODO dynamically add contents of order_payload["addressData"]
        }, 
        **order_payload["addressData"]
    }
    orders.append(new_dict)
如果希望输出内联:

orders_2 = [{**{k: v for k, v in data.items() if k not in ["addressData", "orderItem"]},
             **data["addressData"], ** order_item} for order_item in data["orderItem"]]

完整代码

data = {
    "importDate": "2020-03-18T10:03:19.194336",
    "status": "shipped",
    "orderNumber": 123456,
    "orderItem": [
        {
            "sku": 998877,
            "itemName": "Doomsday device",
            "netCost": 8.7,
            "quantity": 1
        },
        {
            "sku": 665544,
            "itemName": "Fing longerer",
            "netCost": 99.9,
            "quantity": 1
        }
    ],
    "addressData": {
        "recipientCompany": "Planet Express, Inc",
        "recipientName": "Farnsworth",
        "recipientFirstName": "Hubert",
        "recipientStreet": "72nd Street",
        "recipientHouseNumber": None,
        "recipientAnnex": None,
        "recipientZip": "NNY 10023",
        "recipientCity": "New New York",
        "recipientCountry": "USA",
        "recipientEmail": "hubert@farnsworth.com",
        "recipientPhone": "+123 445-566-7789",
        "recipientMobilePhone": "+123 444 555 666 777"
    }
}

def main(order_payload):
    orders = []
    for order_item in order_payload["orderItem"]:
        new_dict = {
            **{
                "orderDate": order_payload["importDate"],
                "sku": order_item["sku"],
                "itemName": order_item["itemName"]
            }, 
            **order_payload["addressData"]
        }
        orders.append(new_dict)
    return orders

orders_1 = main(data)
orders_2 = [{**{k: v for k, v in data.items() if k not in ["addressData", "orderItem"]},
             **order_item, **data["addressData"]} for order_item in data["orderItem"]]

print(orders_1)
# [
#     {
#         "orderDate": "2020-03-18T10:03:19.194336",
#         "sku": 998877,
#         "itemName": "Doomsday device",
#         "recipientCompany": "Planet Express, Inc",
#         "recipientName": "Farnsworth",
#         "recipientFirstName": "Hubert",
#         "recipientStreet": "72nd Street",
#         "recipientHouseNumber": null,
#         "recipientAnnex": null,
#         "recipientZip": "NNY 10023",
#         "recipientCity": "New New York",
#         "recipientCountry": "USA",
#         "recipientEmail": "hubert@farnsworth.com",
#         "recipientPhone": "+123 445-566-7789",
#         "recipientMobilePhone": "+123 444 555 666 777"
#     },
#     {
#         "orderDate": "2020-03-18T10:03:19.194336",
#         "sku": 665544,
#         "itemName": "Fing longerer",
#         "recipientCompany": "Planet Express, Inc",
#         "recipientName": "Farnsworth",
#         "recipientFirstName": "Hubert",
#         "recipientStreet": "72nd Street",
#         "recipientHouseNumber": null,
#         "recipientAnnex": null,
#         "recipientZip": "NNY 10023",
#         "recipientCity": "New New York",
#         "recipientCountry": "USA",
#         "recipientEmail": "hubert@farnsworth.com",
#         "recipientPhone": "+123 445-566-7789",
#         "recipientMobilePhone": "+123 444 555 666 777"
#     }
# ]
print(orders_2)
# [
#     {
#         "importDate": "2020-03-18T10:03:19.194336",
#         "status": "shipped",
#         "orderNumber": 123456,
#         "sku": 998877,
#         "itemName": "Doomsday device",
#         "netCost": 8.7,
#         "quantity": 1,
#         "recipientCompany": "Planet Express, Inc",
#         "recipientName": "Farnsworth",
#         "recipientFirstName": "Hubert",
#         "recipientStreet": "72nd Street",
#         "recipientHouseNumber": null,
#         "recipientAnnex": null,
#         "recipientZip": "NNY 10023",
#         "recipientCity": "New New York",
#         "recipientCountry": "USA",
#         "recipientEmail": "hubert@farnsworth.com",
#         "recipientPhone": "+123 445-566-7789",
#         "recipientMobilePhone": "+123 444 555 666 777"
#     },
#     {
#         "importDate": "2020-03-18T10:03:19.194336",
#         "status": "shipped",
#         "orderNumber": 123456,
#         "sku": 665544,
#         "itemName": "Fing longerer",
#         "netCost": 99.9,
#         "quantity": 1,
#         "recipientCompany": "Planet Express, Inc",
#         "recipientName": "Farnsworth",
#         "recipientFirstName": "Hubert",
#         "recipientStreet": "72nd Street",
#         "recipientHouseNumber": null,
#         "recipientAnnex": null,
#         "recipientZip": "NNY 10023",
#         "recipientCity": "New New York",
#         "recipientCountry": "USA",
#         "recipientEmail": "hubert@farnsworth.com",
#         "recipientPhone": "+123 445-566-7789",
#         "recipientMobilePhone": "+123 444 555 666 777"
#     }
# ]

您在输出csv中查找哪些字段/列,
pandas.json\u normalize()
后跟
to\u csv()
将是创建所需输出的简单方法。您在输出csv中查找哪些字段/列,
pandas.json\u normalize()
后跟
to\u csv()
这将是创建所需输出的简单方法。非常感谢!
**order\u有效载荷[“addressData”]
正是我想要的万分感谢!
**order\u有效载荷[“addressData”]
正是我想要的