【问题标题】:python zip 2 long lists as dictionary truncation errorpython zip 2长列表作为字典截断错误
【发布时间】:2015-10-16 23:45:31
【问题描述】:

我正在使用 python 2.7。 我有 2 个长列表:

id=['avc-asd','asd-red'.....]
name=['car','toy',.....]

print len(id) #600
print len(name) #600

my_dict=dict(zip(id,name))
print len(my_dict) #20
print my_dict
#{'avcf-asd':'car','asd-red':'toy'...}

知道为什么会发生截断吗? :-/


我也尝试过使用 izip_longest,但得到了相同的结果。

    from itertools import izip_longest

        my_dict=dict(izip_longest(id,name))
        print len(my_dict) #20

【问题讨论】:

  • 让我知道这是否符合您的问题。如果是这样,我会将其指定为以下内容:stackoverflow.com/questions/19603120/…
  • 您的id list 有重复项吗?
  • id 列表没有重复但名称是的
  • 检查here
  • 在 Python 2.7.9 中为我工作。必须是列表内容的问题(例如字典不能有重复的键)。你能在这里发布一些能重现问题的东西吗?

标签: python list dictionary zip


【解决方案1】:

我已将我的评论移至答案帖子,因为 OP 表示它解决了问题。

基本上,您需要确保字典的键是唯一的,而且,正如您所指出的,您 zip 事物的顺序很重要。考虑以下示例代码:

>>> ids = ['1', '2', '3']
>>> names = ['a', 'b', 'a']
>>> dict(zip(ids, names))        # works fine; no duplicates in ids
{'1': 'a', '3': 'a', '2': 'b'}
>>> dict(zip(names, ids))        # truncates due to duplicates in names
{'a': '3', 'b': '2'}

【讨论】:

    猜你喜欢
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    相关资源
    最近更新 更多