【问题标题】:Extract integers from tuples stored as a value in a dictionary从存储为字典中的值的元组中提取整数
【发布时间】: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


【解决方案1】:

您可以使用元组解包一次性将它们全部分配。

my_dict = {'String': ('123', '456', '789')}

a,b,c = my_dict['String']

print(a,b,c)

#prints

123 456 789

如果你想让他们成为int,你可以像

a,b,c = [int(x) for x in my_dict['String']]

【讨论】:

  • 它们仍然需要转换为int
  • 使用转换为int的选项更新了答案
  • 好的,这是我从未想过的方式。虽然第一个变体给出了以下错误:cannot unpack non-iterable int object 第二个这个错误:'int' object is not iterable 虽然,@Karl Knechtel 有一点!当我像在示例代码中一样从头开始创建字典时,您的解决方案有效。虽然我的实际字典的语法看起来完全一样。将我的实际代码添加到问题中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-20
相关资源
最近更新 更多