NorthIsUp
NorthIsUp

Reputation: 17867

Get the name of a list item

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 }

Upvotes: 1

Views: 11062

Answers (2)

bignose
bignose

Reputation: 32309

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.

Upvotes: 1

manojlds
manojlds

Reputation: 301147

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.

Upvotes: 0

Related Questions