Python如何将空格分隔的键、值对的字符串转换为字典?
在StackOverFlow上找到一个比较好的方法:
s = '#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 pprint
pprint(entries)
>>> $ python tryme.py
{'#one': 'cat', '#three': 'birds', '#two': 'dogs'}
我平时的用途:
原始数据是网站日志的TOP10 URL
1244544 https://imgs.ipcpu.com/c/309/1631097475470.jpg
1167387 https://imgs.ipcpu.com/c/134/1631097475316.jpg
1122950 https://imgs.ipcpu.com/c/890/1631097477444.jpg
260077 https://imgs.ipcpu.com/c/82/1631105200663.jpg
166589 https://imgs.ipcpu.com/c/134/1631097467635.jpg
经过以下语句处理
outlet = str.split()
entries = dict([(x, y) for x, y in zip(outlet[1::2], outlet[::2])])
print(entries)
最终输出如下
{'https://imgs.ipcpu.com/c/309/1631097475470.jpg': '1244544',
'https://imgs.ipcpu.com/c/134/1631097475316.jpg': '1167387',
'https://imgs.ipcpu.com/c/890/1631097477444.jpg': '1122950',
'https://imgs.ipcpu.com/c/82/1631105200663.jpg': '260077',
'https://imgs.ipcpu.com/c/134/1631097467635.jpg': '166589'}