0

In python I have:

var = "abc"

How can I create a dictionary of name abc using var ?

1
  • 1
    to make the question more clear, could you give us a dictionary that you seek ? Commented Feb 10, 2015 at 4:58

2 Answers 2

2

globals() method returns a dictionary that contains all the names of global scope. You can use this to create a variable whose name is stored in another variable. Something like this:

>>> var = 'abc'
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'var': 'abc', '__doc__': None, '__package__': None}
>>> globals()[var] = {}
>>> abc
{}
>>> globals()
{'abc': {}, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'var': 'abc', '__name__': '__main__', '__doc__': None}
>>> abc['p0'] = 2
>>> abc
{'p0': 2}
>>> 
Sign up to request clarification or add additional context in comments.

2 Comments

locals() is the safer choise if used in a scope.
@Iskren I originally mentioned locals() but later found that it has problem as specified here: stackoverflow.com/a/8028772/377953
0

What do you mean? Assign var to a dictionary where 'name' evaluates to 'abc'? In that case,

var = {'name': 'abc'}

Otherwise, I have no idea what you're asking.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.