如何在python中将不带引号的字符串转换为字典 [英] How to convert string without quotes to dictionary in python

查看:40
本文介绍了如何在python中将不带引号的字符串转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将不带引号的字符串转换成字典.

I have to convert string without quotes into dictionary.

device: 0, name: GeForce GTX 1080 8GB, pci bus id: 0000:01:00.0

设备",名称"和"pci总线ID"必须是密钥,

the 'device', 'name' and 'pci bus id' have to be keys,

和"0","GeForce GTX 1080 8GB","0000:01:00.0"必须为值.

and '0', 'GeForce GTX 1080 8GB', '0000:01:00.0' have to be values.

我是从tensorflow.python.client.list_local_devices()

I get this from tensorflow.python.client.list_local_devices()

推荐答案

使用两个 .split() dictionary comprehension ,第一个 .split(',')分割整个字符串,第二个 split(':')分割要转换为键和值的列表项

Using, two .split()'s and dictionary comprehension, first .split(', ') divides up the entire string, the second split(': ') divides up the items of list to be cast as keys and values

s = "device: 0, name: GeForce GTX 1080 8GB, pci bus id: 0000:01:00.0"
d = {i.split(': ')[0]: i.split(': ')[1] for i in s.split(', ')}

{'device': '0', 'name': 'GeForce GTX 1080 8GB', 'pci bus id': '0000:01:00.0'}

这篇关于如何在python中将不带引号的字符串转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆