从字符串创建字典

编程入门 行业动态 更新时间:2024-10-27 15:24:54
本文介绍了从字符串创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个字符串形式:

s = 'A - 13, B - 14, C - 29, M - 99'

等等(长度不同)。从这个最简单的方法来创建一个字典?

and so on (the length varies). What is the easiest way to create a dictionary from this?

A: 13, B: 14, C: 29 ...

我知道我可以拆分,但是我无法获得正确的语法。如果我在 - 上分裂,那么我如何加入这两个部分?

I know I can split but I can't get the right syntax on how to do it. If I split on -, then how do I join the two parts?

迭代这似乎是痛苦

推荐答案

>>> s = 'A - 13, B - 14, C - 29, M - 99' >>> dict(e.split(' - ') for e in s.split(',')) {'A': '13', 'C': '29', 'B': '14', 'M': '99'}

编辑:下一个解决方案是当你想要的值作为整数,我认为是你想要的。

The next solution is for when you want the values as integers, which I think is what you want.

>>> dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(','))) {'A': 13, ' B': 14, ' M': 99, ' C': 29}

更多推荐

从字符串创建字典

本文发布于:2023-10-28 02:03:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535176.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字典

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!