Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string without quotes to dictionary in python

I have to convert string without quotes into dictionary.

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

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

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

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

like image 936
wuullif56 Avatar asked Jul 21 '26 15:07

wuullif56


1 Answers

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'}
like image 192
vash_the_stampede Avatar answered Jul 23 '26 05:07

vash_the_stampede