Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

First, you have to split the string by ', ' (comma and space) to separate each key : value in your string. After, for each string with 'key: value' you must split it for ': ' (colon and space) to get key and value separately to build your dictionary.

dict = {}
    s = "device: 0, name: GeForce GTX 1080 8GB, pci bus id: 0000:01:00.0"'''split to separate the main string in 'key: value' substrings'''
    key_value = s.split(", ")

'''each substring is separated in key and value to be appended into dictionary'''for v in key_value:
       aux = v.split(": ")
       dict[aux[0]] = aux[1]

    print(dict)

The outuput:

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

Post a Comment for "How To Convert String Without Quotes To Dictionary In Python"