1

I have easy access to a list of variables as such:

[a, b, c,]

I was wondering, can you introspect (or something) on the variable names to get a dict that looks like this:

{ 'a'=a, 'b'=b, 'c'=c }
bignose
  • 30,281
  • 14
  • 77
  • 110
NorthIsUp
  • 17,502
  • 9
  • 29
  • 35
  • 1
    possible duplicate of [Python variables as keys to dict](http://stackoverflow.com/questions/3972872/python-variables-as-keys-to-dict) – Felix Kling May 12 '11 at 23:55
  • Similar question the answer to which you might find helpful: [variable name introspection in Python](http://stackoverflow.com/questions/1894591/variable-name-introspection-in-python) – sneg May 12 '11 at 23:58

2 Answers2

1

The list doesn't “contain variables”. It refers to the objects it contains; just as the names ‘a’, ‘b’, ‘c’ refer to those same objects.

So getting an item from the list gets you the object. That object may have zero, one, or many names; it doesn't know any of them.

If you know at the time you create the list that you will later want to refer to the items by name, then it sounds like you want to create a dict instead.

bignose
  • 30,281
  • 14
  • 77
  • 110
0

Something like below maybe?

dict(zip(arr,arr))

Edit:

From the suggested duplicates, if you want that:

for i in ('a', 'b', 'c'):
   dic[i] = locals()[i]

but you must have the list as ['a','b','c'] If you have it as [a,b,c] the values would have replaced the variable names anyway.

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • You could further shorthand your solution by doing `vars = [i for i in locals() if i and "__" not in i and "<" not in i]; dict(zip(vars,[locals[i] for i in vars]))` – inspectorG4dget May 13 '11 at 00:31