我有一个词典,其中的键是日期格式为'%m /%d /%y',我想分开这个,所以我可以按月绘制值。因此,目标只是将键从m / d / y转换为m,并在字典中保留相同的值。
months = dict.keys()
for i in months:
i = dt.datetime.strptime(i[months],'%m/%d/%y').month
我收到此错误:
TypeError: string indices must be integers
感谢您的任何建议。
答案 0 :(得分:1)
Python不是我的专业知识,但我对编程提供了足够的知识以提供以下内容(而不是对它的势利):
from datetime import datetime
full_dates = ['1/1/17','2/1/17'] # best practice[1] is to use a list since this is an ordered sequence of items on an x-axis. Also, don't use dict since it's a reserved word in Python (it's used to create dictionaries using dict(...), which is the same as creating dict this way btw {...}[2])
months_only = []
for full_date in full_dates:
months_only.append(datetime.strptime(month,'%m/%d/%y').month)
print(months_only) # outputs [1, 2]
[1] In Python, when to use a Dictionary, List or Set?
[2] https://developmentality.wordpress.com/2012/03/30/three-ways-of-creating-dictionaries-in-python/
答案 1 :(得分:0)
months = dict.keys()
for i in months:
i = dt.datetime.strptime(dict[i],'%m/%d/%y').month