【发布时间】:2019-01-17 15:24:24
【问题描述】:
我在 python2.7 中有一个代码,它获取一行文本作为其列表元素并将其作为 json 返回。这是代码:
import itertools
lines=["Hamlet"
,"William Shakespeare",
"Edited Barbara B Mowat Paul Werstine"
,"Michael Poston Rebecca Niles"]
LinesMap=dict()
for line in lines:
list=[l for l in line.split(' ')]
d = dict(itertools.izip_longest(*[iter(list)] * 2, fillvalue=None))
LinesMap.update(d)
print(LinesMap)
输出是:
{'William': 'Shakespeare', 'Edited': 'Barbara', 'B': 'Mowat',
'Michael':'Poston', 'Paul': 'Werstine', 'Rebecca': 'Niles', 'Hamlet': None}
应该是这样的:
{'Hamlet': None, 'William': 'Shakespeare', 'Edited': 'Barbara',
'B':'Mowat', 'Paul': 'Werstine', 'Michael': 'Poston', 'Rebecca': 'Niles'}
如果我把列表加长,那就更糟了!为什么这不是正确的顺序?但是当我在 python3.6 中运行相同的代码时,当然使用 python3 语法,顺序是正确的。 python3.6代码为:
import itertools
lines=["Hamlet"
,"William Shakespeare",
"Edited Barbara B Mowat Paul Werstine"
,"Michael Poston Rebecca Niles"]
LinesMap=dict()
for line in lines:
list=[l for l in line.split(' ')]
d = dict(itertools.zip_longest(*[iter(list)] * 2, fillvalue=None))
LinesMap = {**LinesMap, **d}
print(LinesMap)
这是一个问题。另一个是短名单可以正常运行。但是当列表较长且元素过多时,输出不会显示任何内容,并且似乎已损坏。这是在 Windows 中,在 linux 中它不会中断。有什么问题?
ps:由于某些原因,我必须在 python 2.7 中运行它!
【问题讨论】:
-
字典在 Python 3.6 之前没有排序 - 这意味着您不能依赖早期版本中的任何特定顺序。
-
如果你被限制在 2.7,你可能想试试
from collections import OrderedDict -
还在“Hamlet”中添加一个空格,以便添加“None”条目。
-
看起来您希望它们按输入顺序排列。尝试
from Collections import OrderedDict并使用它而不是dict。
标签: python python-3.x python-2.7 dictionary