Python 2.7解包错误

时间:2016-11-28 01:40:28

标签: python

我收到错误消息

  

badfilesdic = {k:v for k,v in badfilelist} ValueError:需要更多   解包的价值超过1个

我不确定如何解决它!

this is the code:

def badfiles(hasheddic, filesavedin ):

    print hasheddic
    print '\n'
    print filesavedin

    badfilelist = [s.split(' : ') for s in hasheddic]
    badcontentlist = [s.split(' : ') for s in filesavedin]
    badfilesdic = {k: v for k, v in badfilelist}
    badcontentdic = {k: v for v, k in badcontentlist}

    match = ""
    for hashval, filename in badcontentdic.iteritems():
        if filename in badfilesdic:
            match += (hashval + " File Extension:  " + badfilelist[filename]) + "\n"

    return match

2 个答案:

答案 0 :(得分:0)

您需要更正代码:

badfilelist = [s.split(':') for s in hasheddic]

然后

badfilesdic = dict(badfilelist) # if you want to have a unique dict

badfilesdic = [{k:v} for k, v in badfilelist] # if you want to have a list of dicts

of maybe:

badfilesdic = tuple({k:v} for k, v in badfilelist) # if you want to have a tuple of dicts

或任何你喜欢的。您只需要正确解压缩变量。

答案 1 :(得分:-1)

您正在进行的拆包无法按预期工作。当您说k: v for k, v in hasheddic时,您要在(k,v)中的每个元素中声明两个元素hasheddic的元组。如果任何字符串超过长度2,则会出现解包错误。

例如:

s = "hi hi".split()
for a, b in s:
    print a
    print b

返回

h
i
h
i

如果该字符串是,例如" foo bar",您将得到" foo"的解包错误。和" bar"。

如果您确定输入字符串格式正确(split总是返回2个元素列表),则可以这样做:

{x[0]: x[1] for x in badfilelist}