2

I have the variable

street_38 = (4,6,7,12,1,0,5)

Is there a way to actually print the name but not the values? That is I am just interest on getting 'street_38'. I want that because I am plotting a figure and when I put

plt.title(str(street_38)

as title I get the values and not the name

Thanks

hpnk85
  • 395
  • 1
  • 7
  • 12
  • 1
    What is wrong with `plt.title("street_38")`? This is a serious question. Please explain why the literal name isn't useful to you, as that will help people to craft a good solution to your problem. – Robᵩ Jul 06 '16 at 17:41
  • [Doesn't sound like a good idea...](http://stackoverflow.com/questions/544919/can-i-print-original-variables-name-in-python) – Curmudgeon Jul 06 '16 at 17:42
  • 1
    How about this workaround: `street_38 = ('street_38', 4, 6, 7, 12, 1, 0, 5)`? That way `street_38` is the first element of your tuple. – John Perry Jul 06 '16 at 17:43
  • 3
    It sounds like you are using the wrong datatype. Since I am guessing you have more than one street here, it might make sense to turn it into a dictionary like `streets = {'street_38': (4,6,7,12,1,0,5)}` then as you iterate through your streets (what I am guessing you are going to do), just print the key value itself `for street_name, values in streets.items():` `plt.title(street_name)` – taylor swift Jul 06 '16 at 17:44
  • Thanks Kelvin, yes that sounds like a very goo idea – hpnk85 Jul 06 '16 at 17:50
  • Hello use this filter(lambda x: False is x.startswith("__"), vars()) to get list of variable names – Rakesh Kumar Jul 06 '16 at 17:57

2 Answers2

1

From this answer, you could do something like this

 >>> a = 1
 >>> for k, v in list(locals().iteritems()):
         if v is a:
             a_as_str = k
 >>> a_as_str
 a
 >>> type(a_as_str)
 'str'

That being said, this is not a good way to do it. Python objects do not have names. Instead, names have objects. A slight exception to this is the __name__ attribute of functions, but the rule is the same - we just store the name as an attribute. The object itself remains unnamed.

The method above abuses the locals() method. It is not ideal. A better way would be to restructure your data into something like a dictionary. A dictionary is specifically a set of named values.

{
    'street38': (4,6,7,12,1,0,5)
}

The point of a dictionary is this key-value relationship. It's a way to look up a value based on a name, which is exactly what you want. The other problem you may run in to (depending on what you're doing here) is what will happen if there are thousands of streets. Surely you don't want to write out thousands of variable names too.

Community
  • 1
  • 1
Jamie Counsell
  • 7,730
  • 6
  • 46
  • 81
0

There isn't a good way to do this programatically. Ideally, the name of a variable carries no meaning to the code at all. It's only useful in conveying ideas to the programmer so that they know what they are working with.

mgilson
  • 300,191
  • 65
  • 633
  • 696