加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 将变量转换为dictonaries

发布时间:2020-12-20 12:24:05 所属栏目:Python 来源:网络整理
导读:我有类似这样的东西,其中trade_date,effective_date和termination_date是日期值: tradedates = dict(((k,k.strftime('%Y-%m-%d')) for k in (trade_date,effective_date,termination_date))) 我明白了: {datetime.date(2005,7,25): '2005-07-25',datetime.
我有类似这样的东西,其中trade_date,effective_date和termination_date是日期值:

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

我明白了:

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

我想要的是:

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

我该如何实现这一目标?

解决方法

使用 vars

>>> import datetime
>>>
>>> trade_date = datetime.date(2005,25)
>>> effective_date = datetime.datetime(2005,38)
>>> termination_date = datetime.datetime(2010,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'}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读