最新消息:

Python如何将空格分隔的键、值对的字符串转换为字典

IT技术 ipcpu 50浏览 0评论

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'}

参考资料

https://stackoverflow.com/questions/35618307/how-to-transform-string-of-space-separated-key-value-pairs-of-unique-words-into

转载请注明:IPCPU-网络之路 » Python如何将空格分隔的键、值对的字符串转换为字典

发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址