How to get a Variable Name as a String in Python

In this tutorial, we will learn how to get a variable name as a string in Python. We will understand this concept with the help of an example.

Variables in Python

Variables are any values whose value is not fixed, therefore, they can be updated as per the required condition. There are two types of variables,i.e, Global variables and Local variables.

In Python, we do not require to declare the variable and the data type of the variable is also not required.

To update the value of the variable, just assign it a new value later on.

Get a Variable Name as a String

To get a variable name as a string in Python we use the iteritems() or the items() method. This is basically a process of searching for a variable name with the help of a reverse approach.

Syntax: dictionary.items()

Parameters: It is important to know that this method does not take any parameters.

Code

Let’s understand with the help of the following example:

var = 710
variable_name = [k for k, v in locals().items() if v == 710][0] 
print("Your variable name is " + variable_name)

Output:

Your variable name is var

Using iteritems() in Python3 produces:

AttributeError: 'dict' object has no attribute 'iteritems'

Explanation:

  • Input any variable whose name we will get as a string.
  • Use the local() to get the dictionary of the current local table.
  • Use the items() to get the variable name and print the variable name in form of a string.

I hope you were able to understand this concept. Feel free to ask any questions regarding this concept or any other topic you want to know about.

You can also learn about: Python String decode() method in Python and groups() method in Regular Expression.

One response to “How to get a Variable Name as a String in Python”

  1. Ruslan says:

    A small mistake in explanation.
    ‘local()’ should be changed to ‘locals()’ instead.

Leave a Reply

Your email address will not be published. Required fields are marked *