访问字典项错误:TypeError:元组索引必须是整数或切片,而不是字符串

huangapple go评论65阅读模式
英文:

Accessing Dict item error: TypeError: tuple indices must be integers or slices, not str

问题

以下是您要翻译的内容:

我正在编写一个用于处理来自项目字典的数据项的类。在这里,我遇到了这个错误:

字典函数的代码(简要)

def preProcess():
    dataset = {}
    for i, v in enumerate(items):
        dataset[v['image_id']] = {'image': v['file_name']}, {
                                  'texts': {i: v['sent']}}
                    
    return dataset

访问字典项的代码

for idx, val in enumerate(data):
    print(self.data[idx]['image'])

字典函数工作得很好,但当我尝试访问项目时,它会产生以下错误:

类型错误:元组索引必须是整数或切片,而不是字符串

我想它把字典视为元组。我对Python的这些数据结构是新手。有人可以指出问题出在哪里吗?我是不是在插入或声明字典项时做错了什么?

提前感谢。

英文:

So I was writing a class for processing data items from a dictionary of items. Here I am having this error:

> The code of dictionary function is (in brief)

def preProcess():
    dataset = {}
    for i, v in enumerate(items')):
        dataset[v['image_id']] = {'image' : v['file_name']}, { 
                                  'texts' : {i : v['sent']}}
                    
    return dataset

> The code of accessing the dictionary item is

for idx, val in enumerate(data):
    print(self.data[idx]['image'])

The dictionary function works perfectly but when I try to access the items, it gives following error:

> TypeError: tuple indices must be integers or slices, not str

Its considering the dict as a tuple I guess. I am new to such data structures of Python. Could anyone please point out where the issue is? Am I inserting or declaring dictionary items wrong?
Thanks in Advance.

答案1

得分: 0

所以我的字典初始化不正确。我通过导入collections.defaultdict来解决这个问题。

dataset = defaultdict(dict)
dataset[w['image_id']]['image'] = v['file_name']
dataset[w['image_id']]['texts'] = {}
dataset[w['image_id']]['texts'][inner_i] = inner_v['sent']
英文:

So my dictionary initialization was not correct. I solved the issue by importing collections.defaultdict

dataset = defaultdict(dict)
dataset[w['image_id']]['image'] = v['file_name']
dataset[w['image_id']]['texts'] = {}
dataset[w['image_id']]['texts'][inner_i] = inner_v['sent']

huangapple
  • 本文由 发表于 2023年5月10日 21:11:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76218850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定