【发布时间】:2017-04-27 13:08:12
【问题描述】:
我对下面的代码有点疑惑:
Python 2.7.13 (default, Jan 19 2017, 14:48:08)
[GCC 6.3.0 20170118] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> list_a = ['300', '300', '200', '150', '150', '120', '1']
>>> list_b = ['butter', 'sugar', 'yolks', 'flour', 'potato_starch', 'egg_whites', 'lemon_zest']
>>> c = dict(zip(list_b, list_a))
>>> print c
>>>{'butter': '300', 'lemon_zest': '1', 'flour': '150', 'egg_whites': '120', 'sugar': '300', 'yolks': '200', 'potato_starch': '150'}
>>> c = dict(zip(list_a, list_b))
>>> print c
>>>{'300': 'sugar', '200': 'yolks', '1': 'lemon_zest', '120': 'egg_whites', '150': 'potato_starch'}
为什么通过反转列表,字典“c”会丢失两对“成分:数量”?
我注意到最多 6 双就可以了。
我为不完整的解释道歉,但我不知道如何向我解释这是一个异常。
感谢愿意帮助我理解的人。
【问题讨论】:
-
字典键必须是唯一的。如果您从
list_a创建密钥,则它包含重复项,因此您会覆盖针对该密钥存储的任何现有数据。
标签: python python-2.7 list dictionary