最新消息:20210917 已从crifan.com换到crifan.org

【已解决】python 3中dict取值报错:not enough values to unpack (expected 3, got 2)

Python crifan 7314浏览 0评论

Python代码:

        announcementStrList = [
            "^更新公告$", # strict full match
            "^游戏公告$", # strict full match
        ]
        isAnnouncement = False
        foundResultDict, imgPath = self.isWordsInCurScreen(announcementStrList)
        for eachPossibleStr in announcementStrList:
            curIsFound, _, curImgPath = foundResultDict[eachPossibleStr]

其中返回的foundResultDict,是一个dict,且值是希望的,正常的值:

{'^更新公告$': (True, (...)), '^游戏公告$': (True, (...))}

但是调试时报错:

发生异常: ValueError
not enough values to unpack (expected 3, got 2)

看起来,估计是:

dict(变量foundResultDict)中的key是特殊的字符串,此处的 “^更新公告$”,导致了此处错误

去研究看看如何解决

python dict not enough values to unpack (expected 3, got 2)

Python 3 – ValueError: not enough values to unpack (expected 3, got 2) – Stack Overflow

python – not enough values to unpack (expected 2, got 1 – Stack Overflow

python – ValueError: not enough values to unpack (expected 3, got 2) – Stack Overflow

然后才注意到的是:

其实不是上述dict中key是特殊字符导致的,而是:

获取dict的值后,只有2项:

(True, (...))

但是却被赋值给了3个变量

curIsFound, _, curImgPath

而之所以把变量个数搞错,是因为刚才在优化函数isWordsInCurScreen,改动了之前返回值的逻辑。

所以此处解决办法很简单,去改为:

curIsFound, _ = foundResultDict[eachPossibleStr]

即可。

【总结】

此处python中的dict报错:

not enough values to unpack (expected 3, got 2)

的原因:

不是:看起来的,以为的,dict中的key,’^更新公告$’,以为是包含特殊字符,导致无法获取到dict中的值呢

实际上是:通过key,获取了dict的值,返回后,本来只有2部分,却给了3个变量

即:

twoPartTupleDict = {
  "theKey": ("part1", “part2")
}

但是却:

(value1, value2, value3) = twoPartTupleDict["theKey"]

导致报错的。

实际上应该是:

(value1, value2) = twoPartTupleDict["theKey"]

所以此处把:

curIsFound, _, curImgPath = foundResultDict[eachPossibleStr]

改为:

curIsFound, _ = foundResultDict[eachPossibleStr]

即可。

【后记】

专门对于StackOverflow中相关帖子去给出了详尽的回答。

此处贴出核心演示代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)'
# Author: Crifan Li
# Update: 20191212
def notEnoughUnpack():
    """Showing how to understand python error `not enough values to unpack (expected 3, got 2)`"""
    # a dict, which single key's value is two part tuple
    valueIsTwoPartTupleDict = {
        "name1": ("lastname1", "email1"),
        "name2": ("lastname2", "email2"),
    }

    # Test case 1: got value from key
    gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK
    print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail))
    # gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2)


    # Test case 2: got from dict.items()
    for eachKey, eachValues in valueIsTwoPartTupleDict.items():
        print("eachKey=%s, eachValues=%s" % (eachKey, eachValues))
    # same as following:
    # Background knowledge: each of dict.items() return (key, values)
    # here above eachValues is a tuple of two parts
    for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items():
        print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2))
    # but following:
    for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2)
        pass


if __name__ == "__main__":
    notEnoughUnpack()

和截图:

更多细节详见:

Python 3 – ValueError: not enough values to unpack (expected 3, got 2) – Stack Overflow

转载请注明:在路上 » 【已解决】python 3中dict取值报错:not enough values to unpack (expected 3, got 2)

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
92 queries in 0.191 seconds, using 23.32MB memory