字典列表:python 2.7中的打印可读输出

时间:2016-03-21 16:48:01

标签: python list python-2.7 dictionary

我尝试从3D软件包中输出大量信息,并努力寻找一种以可读的格式格式化数据的好方法,然后再将其同步到在线服务器。

我很想知道如何获得这个的打印输出:

dicts = [
    { "Annot1": 1, "NAME": "name", "TEXT": "text" },
    { "Annot2": 2, "NAME": "name", "TEXT": "text" },
    { "Annot3": 3, "NAME": "name", "TEXT": "text" },
    { "Annot4": 4, "NAME": "name", "TEXT": "text" }
]
print "\n \n".join(str(i)+" "+str(a) for i, a in enumerate(dicts, start=1))

看起来像这样的打印输出:

name = {
    "Annot1": 'name',
    "Annot2": 'name',
    "Annot3": 'name',
    "Annot4": 'name'
}
text = {
    "Annot1": 'text',
    "Annot2": 'text',
    "Annot3": 'text',
    "Annot4": 'text'
}
for key in sorted(name):
    print key
    print "NAME: %s" % name[key]
    print "TEXT: %s" % text[key]
    print

......这就是我提出的

dicts = [
    { "Annotation_1": 1, "NAME": "name", "CONTENT": "text" },
    { "Annotation_2": 2, "NAME": "name", "CONTENT": "text" },
    { "Annotation_3": 3, "NAME": "name", "CONTENT": "text" },
    { "Annotation_4": 4, "NAME": "name", "CONTENT": "text" }
]

for d in dicts:
name = ''             # Or just name = 'Annot1' ?
for k in d.keys():
    if k.startswith('Annot'):
        name = k
        break
print d['Annotation'], name
print("NAME: %s" % d['NAME'])
print("CONTENT: %s" % d['CONTENT'])
print

这就是我打算从我的3D应用程序中输入将要写入文件的数据的方式

dicts=[]

annotations={}
annotation[("Annotation_" + str(i))]
annotation['NAME'] = 'name'
annotation['CONTENT'] = 'content'
annotation['REF_URL'] = 'ref_url'
annotation['REF_INFO'] = 'ref_nfo' 

dicts.append(annotations)

这是我到目前为止基于我得到的帮助而提出的。

这是一个很好的方法吗? (到目前为止,初始的范围循环只是一个占位符)

annotations = []

for d in range(10):
    annotations.append(dict(
    [('ID', d+1),
    ('NAME', 'Tag Name '+str(d+1)),
    ('CONTENT', 'Note Content: This space will have a lot of text'),
    ('URL', 'ref address'),
    ('URL Info', 'url info')]
    ))

for i, a in enumerate(annotations):
    print "\nAnnotation:", "#"+str(i+1)
    print "NAME:", a['NAME']
    print "NOTE CONTENT:", a['CONTENT']
    print "Ref URL:", a['URL']
    print "URL Info:", a['URL Info']

2 个答案:

答案 0 :(得分:0)

据我了解你,你只想要这个:

for d in dicts:
    name = ''             # Or just name = 'Annot1' ?
    for k in d.keys():
        if k.startswith('Annot'):
            name = k
            break
    print(name)
    print("NAME: %s" % d['NAME'])
    print("TEXT: %s" % d['TEXT'])
    print()

答案 1 :(得分:0)

此:

dicts = [
 { "Annot1": 1, "NAME": "name", "TEXT": "text" },
 { "Annot1": 2, "NAME": "name", "TEXT": "text" },
 { "Annot1": 3, "NAME": "name", "TEXT": "text" },
 { "Annot1": 4, "NAME": "name", "TEXT": "text" }
]

for d in dicts:
    print "Annot{}".format(d["Annot1"])
    for item in ["NAME", "TEXT"]:
        print '{}: {}'.format(item, d[item])
    print

给出了这个输出:

Annot1
NAME: name
TEXT: text

Annot2
NAME: name
TEXT: text

Annot3
NAME: name
TEXT: text

Annot4
NAME: name
TEXT: text