-1

I have a list with two item, each item is a dictionary. now I want to print the item but as these are dicts, python writes the dicts and not the name. any suggestion?

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' )
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Fatemeh
  • 63
  • 6

2 Answers2

2

My suggestion is that you use a dict for sep, instead of a list. That way you could make the dict names as string-keys for them:

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

As you can see in this other question, it's impossible to access instance names, unless you subclass dict and pass a name to the constructor of your custom class, so that your custom dict instance can have a name that you can have access to.

So in that case, I suggest that you use dicts with name-keys to store your dicts, instead of a list.

Community
  • 1
  • 1
Ericson Willians
  • 7,606
  • 11
  • 63
  • 114
1

As sep is a list of variables storing the dictionaries, when you try to print sep you will print the dictionaries.

If you really need to print each variable name as a string, one way to do that is this to also create an other list with the variable names as strings:

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

Then you can do the rest of your code.

Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48