When appending dictionary to a list, dict. not on a new line each time

空扰寡人 提交于 2019-12-24 08:41:44

问题


I have this function that pushes a dictionary created by another function, to a list. The problem I'm having with my code is that multiple pushes do not show up in the list each in a new line. I've tried many ways, but none have given me the desired results.

This is the line the pushes the created dictionary:

Database.xoomDatabase.append(ordenOrganiz)

This function creates the dictionary:

def orderZoom(self):
        nombre = contents1
        nicenum = orderResult
        email = contents2
        num = contents3
        fechaentrega = contents5

        global ordenOrganiz
        ordenOrganiz = {"Num Orden": nicenum,
                        "Nombre": nombre, 
                        "Email": email,
                        "Num Tel/Cel": num,
                        "Fecha de Entrega": fechaentrega}
        return ordenOrganiz

Any ideas on getting this done?


回答1:


Sounds like your problem is not the inserts but rather the "pretty print" that you want to apply, check out the following example that uses json.dumps:

import json

ordenOrganiz = {"Num Orden": 1,
                "Nombre": 2, 
                "Email": 3,
                "Num Tel/Cel": 4,
                "Fecha de Entrega": 5}
lst = []
lst.append(ordenOrganiz)                
lst.append(ordenOrganiz)                

print json.dumps(lst, indent=4, separators=(',', ': '))

OUTPUT

[
    {
        "Fecha de Entrega": 5,
        "Nombre": 2,
        "Num Tel/Cel": 4,
        "Num Orden": 1,
        "Email": 3
    },
    {
        "Fecha de Entrega": 5,
        "Nombre": 2,
        "Num Tel/Cel": 4,
        "Num Orden": 1,
        "Email": 3
    }
]


来源:https://stackoverflow.com/questions/30929275/when-appending-dictionary-to-a-list-dict-not-on-a-new-line-each-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!