Reputation: 13
How can I assign a string value as an empty dictionary in Python? For example,
print hdr
AB_1_15_Oct_2015
hdr = {}
hdr
{}
But I want AB_1_15_Oct_2015
to be an empty dictionary.
Upvotes: 1
Views: 1181
Reputation: 2033
Took a while to figure out, but try this:
hdr = "AB_1_15_Oct_2015"
print hdr
locals()[hdr] = {}
print AB_1_15_Oct_2015
Output:
AB_1_15_Oct_2015
{}
Upvotes: 1
Reputation: 140
If you are saying you want a dictionary named "AB_1_15_Oct_2015". You need to explicitly define a dictionary named:
AB_1_15_Oct_2015 = {}
If you mean you want to be able to set a variable name based off of a value in a string, then there is no way to accomplish this. Also, I can't think of a reason that you would want to. Variable names are only used internally in the code and therefore being able to change variable names based on the date wouldn't help you track a specific date. Without more information on what you are trying to accomplish, it's hard to be able to tell what you need, but I think something like this would accomplish what you want:
hdr = {
"identifier": "AB_1_15_Oct_2015",
"data": whatever_you_wanted_to_store
}
that way that identifier is attached to the data in an accessible way.
Upvotes: 0
Reputation: 375
It's often considered a bad practice to dynamically assign variables like that. There are ways to do so, for instance using exec, but it is dangerous. A better idea would be to use a dictionary, since dynamically creating keys and values is simple. Slightly modifying your existing code:
hdr = "AB_1_15_Oct_2015"
someDict = {}
someDict[hdr] = {}
Then you could access it either from the top level
someDict[hdr]['a'] = "spam"
Or by assigning another variable to reference it:
hdrDict = someDict[hdr]
hdrDict['b'] = "parrot"
Upvotes: 1