【发布时间】:2020-07-16 20:39:46
【问题描述】:
我正在尝试提取存储为元组的整数作为字典中的值。
my_dict = {'String': ('123', '456', '789')}
目标:
a = 123
b = 456
c = 789
我试过了
for k,v in my_dict.items():
a = v[0]
或者通过改变for循环
for item in my_dict.values():
a = item[0]
对于两个版本:
'int' object is not subscriptable
为什么是int?这不是元组吗?
我尝试了一些我已经忘记的其他选项,但也没有用。 到现在我才学习 python 一个月,所以我希望我在这里遗漏了一些明显的东西。
感谢任何提示!
干杯, 弗洛里安
更新 1: 我的实际代码。最后三行是我将列表元素作为值添加到 my_dict 的地方
my_dict = dict()
for x in file_handle:
if "string" in x:
y = x.strip()
z = y[7:-8]
my_dict[z] = my_dict.get(z,0) + 1
elif "date" in x:
cleanedup = x.strip()
titledate = cleanedup[23:-27]
# titledate = titledate.replace("-", ",")
year = titledate[:4]
month = titledate[5:-3]
month = month.lstrip("0")
day = titledate[8:]
day = day.lstrip("0")
titledate = list()
titledate.append(year)
titledate.append(month)
titledate.append(day)
my_dict[z] = my_dict.get(z, 0) + 1
my_dict_temp = {z: (year, month, day)}
my_dict.update(my_dict_temp)
更新 2: 这个的应用是,我想检查存储为元组的日期是否作为 my_dict 中的值在今天的日期范围内 - 7 天
import datetime
today = datetime.date.today()
margin = datetime.timedelta(days = 7)
for k,v in my_dict.items():
if today - margin <= datetime.date(v):
print("Within date range")
我收到以下错误: 函数缺少必需的参数“月”(位置 2)
当我将 if 语句更改为
if today - margin <= datetime.date(v[0], v[1], v[2]):
-> 'int' 对象不可下标
【问题讨论】:
-
您显示的代码有效。错误必须在其他地方;据推测,
my_dict并不像您期望的那样。请尝试生成一个可以单独测试并产生错误的最小示例。
标签: python dictionary integer key-value