How to use a dictionary

Is it possible to return a variable and its value in a dictionary?
For example:

a = 5

{ a : 5 }

In general, no. In the case of “garden-variety” variable names (as opposed, say, to function names), you can’t reverse-engineer from a value to a variable. The most obvious reason is that in Python, many variables may have the same value. Which would you select?

It seems that you can write some code that delves “under the hood” of the interpreter, looking into the stack using the inspect module, but this is dangerous, allowing for malicious intrusion.

Do you have a clearcut idea of just what functionality you want?

a = 5
d = {a:5}
a = 7
b = 5


{5: 5}  # 1st print() call
{5: 5}  # 2d print() call
5       # 3d print() call
Traceback (most recent call last):   # 4th print() call
  File "C:\path\to\", line 9, in <module>
KeyError: 7

If you are willing to list your variables as strings, you can do it:

d = {}
a,b,c = 1,2,3
for var in ['a','b','c']:
    d[var] = eval(str(var))



{'a': 1, 'b': 2, 'c': 3}

a variable isn’t a value, you must mean something else.

dictionary keys are very much like variables, but usually you already have the key or you wouldn’t know which key-value pair you’re after anyway, making it pointless to return the key and the value.

representing things as data rather than code is often more flexible. if you care about something having the name a then that’s data and should be treated as such.

The line between data and code is a bit blurry since code can represent information and data can represent action. They’re both stored in memory with no special separation and are in some sense the same thing.

@patrickd314 nothing dangerous comes from digging around. If something is done wrong then that’s a bug same as any other, doesn’t matter where.

1 Like