Reputation: 41
I'm trying to extract integers stored as a tuple as the value in a dictionary.
my_dict = {'String': ('123', '456', '789')}
Goal:
a = 123
b = 456
c = 789
I've tried
for k,v in my_dict.items():
a = v[0]
Or by changing the for loop
for item in my_dict.values():
a = item[0]
For both versions:
'int' object is not subscriptable
Why the heck int
? Isn't this a tuple?
I've tried a handful of other options I've already forgot but didn't work either. I've been only learning python for a month by now, so I hope I'm missing something obvious here.
Any hint is appreciated!
Cheers, Florian
Update 1: My actual code. The last three lines are where I add the list elements as the values to 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)
Update 2: The application of this is, I want to check if the date stored as a tuple as the value in my_dict is within the date range of today - 7 days
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")
I get the following error: function missing required argument 'month' (pos 2)
When I change the if-statement to
if today - margin <= datetime.date(v[0], v[1], v[2]):
-> 'int' object is not subscriptable
Upvotes: 1
Views: 962
Reputation: 3686
You can use tuple unpacking to assign them all in one go.
my_dict = {'String': ('123', '456', '789')}
a,b,c = my_dict['String']
print(a,b,c)
#prints
123 456 789
If you'd want them as int
you could something like
a,b,c = [int(x) for x in my_dict['String']]
Upvotes: 2