我认为您实际上想要这样的东西:
s = '#one cat #two dogs #three birds'out = s.split()entries = dict([(x, y) for x, y in zip(out[::2], out[1::2])])
这段代码在做什么?让我们分解一下。首先,我们
s按空格将
out其拆分为您所拥有的。
接下来,我们遍历对中的对
out,将它们称为“
x, y”。这些对成为
list元组/对。
dict()接受大小为2的元组的列表,并将其视为
key, val。
这是我尝试时得到的:
$ cat tryme.pys = '#one cat #two dogs #three birds'out = s.split()entries = dict([(x, y) for x, y in zip(out[::2], out[1::2])])from pprint import pprintpprint(entries)$ python tryme.py{'#one': 'cat', '#three': 'birds', '#two': 'dogs'}


