I have a problem with accessing an dictionary AS item like this:
def T():
AS = {"fen": {'used': 0, 'to_end': None, 'depth': 1, 'type': 'normal'}}
return {fen: (data['to_end'], data['type']) for fen, data in AS.items() if data['to_end'] is not True}
s = "fen"
AS = T()
if s in AS and AS[s]['used'] == 0:
print(AS)
gives this error :
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[37], line 7
4 s = "fen"
5 AS = T()
----> 7 if s in AS and AS[s]['used'] == 0:
8 # Tisk hodnot
9 print(AS)
TypeError: tuple indices must be integers or slices, not str
I know a workaround but I wish to grasp in detail why this approach fails. (and how to fix it with a minimum amount of effort)
8
In your T() function, you return a dictionary where the values are tuples, not dictionaries. When you try to access AS[s][‘used’], you’re attempting to use string indexing on a tuple, which is not possible – hence the error “tuple indices must be integers or slices, not str”.
here is a slightly modified version of the code snippet.
def T():
AS = {"fen": {'used': 0, 'to_end': None, 'depth': 1, 'type': 'normal'}}
return {fen: data for fen, data in AS.items() if data['to_end'] is not None}
s = "fen"
AS = T()
if s in AS and AS[s]['used'] == 0:
print(AS)
I also changed the condition if data['to_end'] is not True
to if data['to_end'] is not None
. This is because in your original dictionary, ‘to_end’ was set to None, not True. You can change this if you want to.
You should do :
if s in AS and AS[s][0] == 0:
instead of
if s in AS and AS[s]['used'] == 0:
By doing AS[s]
you access the value of the dict associated with the key s
. The value is a tuple, you cannot acces a tuple value by label, you have to use an index to access a tuple value. Here the index of the data you’re looking for is 0
.