遍历字典的values()

时间:2020-05-15 18:47:08

标签: python python-3.x loops dictionary iteration

我试图通过使用for循环来标记字典的每个值,但我遇到一个错误:“ float”对象不可迭代。 我的代码是:

for doc, answers in answers.items():
    for answer in answers:
        if doc not in tokenized_answers:
            tokenized_answers[doc] = [tokenize(answer, tokenizer)]
        else:
            tokenized_answers[doc].append(tokenize(answer, tokenizer))

在线显示错误:答案中的答案

我如何遍历dict.values()的值?

2 个答案:

答案 0 :(得分:0)

for doc, something_other_than_answers in answers.items():
   ...

答案 1 :(得分:0)

您的答案之一似乎不是避免错误的迭代器,并且仅在可迭代对象上运行,您可以尝试一下,除了检查TypeError之外

 for doc, answers_items in answers.items():
    try: 
        for answer in answers_items:
            if doc not in tokenized_answers:
                tokenized_answers[doc] = [tokenize(answer, tokenizer)]
            else:
                tokenized_answers[doc].append(tokenize(answer, tokenizer))
    except TypeError:
        continue

万一它不是像float那样可迭代的话,它将跳过for循环的答案值。