【问题标题】:ValueError: need more than 1 value to unpack while creating a dictionaryValueError:创建字典时需要多于 1 个值才能解压
【发布时间】:2018-03-14 21:23:45
【问题描述】:

如下所示,我正在尝试使用现有列表创建一个新字典(学生):键和值;

Values 列表的其中一个元素已经在外部定义为课程列表。

student = {}
keys = ['name', 'age', 'courses']

courses = ['Python', 'Linux', 'Selenium Webdriver']

values = ['Kapil', '29', courses]

student = {key:value for key, value in zip(keys + values)}

print (student)

当我运行它时,我得到以下错误:

Error while creating dictionary

【问题讨论】:

  • zip(keys + values) => zip(keys,values)

标签: python-2.7 dictionary


【解决方案1】:

什么时候做

for key, value in zip(keys + values)

zip 产生一个由 1 个元素组成的 tuple,遍历与 values 连接的 keys 列表(zip 可以接受 1 到任意数量的参数),并且 1 个值不适合 2 个目标值。所以你并没有真正用值压缩键,而是添加它们......

你需要:

for key, value in zip(keys,values)

在你的情况下,你最好将元组直接传递给dict 而不是dict理解:

student = dict(zip(keys,values))

【讨论】:

    猜你喜欢
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多