Convert variables to dictators

I have something like this where trade_date, effective_date and term_date are date values:

tradedates = dict(((k, k.strftime('%Y-%m-%d')) 
  for k in (trade_date,effective_date,termination_date)))

I get this:

{datetime.date(2005, 7, 25): '2005-07-25',
 datetime.datetime(2005, 7, 27, 11, 26, 38): '2005-07-27',
 datetime.datetime(2010, 7, 26, 11, 26, 38): '2010-07-26'}

I would like to:

{'trade_date':'2005-07-25','effective_date':'2005-07-27','termination_date':'2010-07-26'}

How do I achieve this?

+3
source share
3 answers

Usage vars:

>>> import datetime
>>>
>>> trade_date = datetime.date(2005, 7, 25)
>>> effective_date = datetime.datetime(2005, 7, 27, 11, 26, 38)
>>> termination_date = datetime.datetime(2010, 7, 26, 11, 26, 38)
>>>
>>> d = vars() # You can access the variable as d['name']
>>> tradedates = {
...     name: d[name].strftime('%Y-%m-%d')
...     for name in ('trade_date', 'effective_date', 'termination_date')
... }
>>> tradedates
{'effective_date': '2005-07-27', 'termination_date': '2010-07-26', 'trade_date': '2005-07-25'}
+8
source

For something of this size, I would create dictdirectly:

result = {
    'trade_date': format(trade_date, '%Y-%m-%d'),
    'effective_date': format(effective_date, '%Y-%m-%d'),
    # etc....
}
+4
source

I am not sure if I received your question correctly. But let me explain what I understood and answer this question:

You know the variable names: trade_date, effective_date, term_date And they have data in them

You can easily do:

tradedates = dict()
for k in ('trade_date','effective_date','termination_date'):
    tradedates[k] = eval(k).strftime('%Y-%m-%d')      // eval will evaluate them as a variable name not as a string.

This will give you the final dict something like:

{
  'trade_date': <date_string_according_to_the_format_above>
  'effective_date': <date_string_according_to_the_format_above>
  'termination_date': <date_string_according_to_the_format_above>
}
0
source

All Articles