简体   繁体   中英

Print list items - python

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM