打印列表项-python

打印列表项-python,python,Python,我有一个有两个项目的列表,每个项目都是一本字典。现在我想打印该项,但由于它们是dict,python编写dict而不是名称。有什么建议吗 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.key

我有一个有两个项目的列表,每个项目都是一本字典。现在我想打印该项,但由于它们是dict,python编写dict而不是名称。有什么建议吗

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' )

我的建议是你在九月使用口述,而不是列表。这样,您就可以将dict名称作为字符串键:

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')
正如您在中所看到的,不可能访问实例名称,除非您将dict子类化并将名称传递给自定义类的构造函数,以便自定义dict实例可以具有您可以访问的名称


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

因为
sep
是存储
词典的
变量列表,当您尝试打印
sep
时,您将打印
词典

如果确实需要将每个
变量
名称打印为
字符串
,一种方法是创建另一个
列表
,其中
变量
名称为字符串:

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

然后你可以完成剩下的代码。

你能添加预期的输出吗?
dict
s没有名字。这是对变量如何工作的误解。您可以将
名称
键放在
dict
中,如果您需要,可以查找。@BhargavRao:它不写“sep_st”,而是写整个字典,而不仅仅是名称。您的意思是要像这样打印
变量
“sep_st”?这就是您想要的输出?