2015-05-30 146 views
-1

我有一个列表与两个项目,每个项目是一个字典。现在我想打印这个项目,但是因为这些都是字符串,所以python写的是字典而不是名字。任何建议?打印列表项目 - python

sep_st = {0.0: [1.0, 'LBRG'], 0.26: [31.0, 'STIG']}  
sep_dy = {0.61: [29.0, 'STIG'], 0.09: [25.0, 'STIG']} 
sep = [sep_st, sep_dy] 
for item in sep: 
    for values in sorted(item.keys()): 
    p.write (str(item)) # here is where I want to write just the name of list element into a file 
    p.write (str(values)) 
    p.write (str(item[values]) +'\n') 
+2

您可以添加预期的输出吗? –

+1

'字典'没有名字。这是对变量如何工作的误解。你可以在'dict'里面放一个'name'键,如果这是你需要的,就查找它。 – khelwood

+0

@BhargavRao:而不是“sep_st”它写入整个字典,而不只是名称 – Fatemeh

回答

2

我的建议是,你使用字典而不是列表。这样,你可以使字典的名称作为字符串键为他们:

sep_st = {0.0: [1.0, 'LBRG'], 0.26: [31.0, 'STIG']}  
sep_dy = {0.61: [29.0, 'STIG'], 0.09: [25.0, 'STIG']} 
sep = {"sep_st": sep_st, "sep_dy": sep_dy} # dict instead of list 
for item in sep: 
    for values in sorted(sep[item].keys()): 
    p.write (str(item)) 
    p.write (str(values)) 
    p.write (str(sep[item][values]) +'\n') 

正如你可以this other question看到,这是不可能的访问实例名,除非你子类字典,并通过一个名称自定义的构造函数类,以便您的自定义词典实例可以拥有一个您可以访问的名称。

因此,在这种情况下,我建议您使用带有名称键的字典来存储您的字典,而不是列表。

1

由于sepvariables存储dictionaries一个列表中,当您尝试打印sep您将打印dictionaries

如果你真的需要打印每variable为做一个string,一种方式是这也创造了其他listvariable名称作为字符串:

sep_st = {0.0: [1.0, 'LBRG'], 0.26: [31.0, 'STIG']}  
sep_dy = {0.61: [29.0, 'STIG'], 0.09: [25.0, 'STIG']} 
sep = [sep_st, sep_dy] 
sep_name = ['sep_st', 'sep_dy'] 
for i in sep_name: 
    print i 

然后,你可以做剩下的代码。