HELLO,
I need to convert this kind of string
to down dict
string = "OS: Windows 7 SP1, Windows 8.1, Windows 10 (64bit versions only)Processor: Intel Core i5 2400s @ 2.5 GHz, AMD FX 6120 @ 3.5 GHz or betterMemory: 6 GB RAMGraphics: NVIDIA GeForce GTX 660 with 2 GB VRAM or AMD Radeon HD 7870, with 2 GB VRAM or better - See supported List"
DICT
requirements={ 'Os':'Windows 7 SP1, Windows 8.1, Windows 10 (64bit versions only)', 'Processor':' Intel Core i5 2400s @ 2.5 GHz, AMD FX 6120 @ 3.5 GHz or better', 'Memory':'6 GB RAM', 'Graphics':'VIDIA GeForce GTX 660 with 2 GB VRAM or AMD Radeon HD 7870, with 2 GB VRAM or better - See supported List', }
and i tried this
string = string.split(':')
and stored each list with the dict like this
requirements['Os'] = string[0] requirements['Processor'] = string[1]
but this is not the right way to do it! which brings me lot more errors. So, is there any custom functions or module for these things ?
Advertisement
Answer
I’d use a regex to just capture the text that you want, since the actual format of the input string won’t be changing. This should give you want:
import re string = "OS: Windows 7 SP1, Windows 8.1, Windows 10 (64bit versions only)Processor: Intel Core i5 2400s @ 2.5 GHz, AMD FX 6120 @ 3.5 GHz or betterMemory: 6 GB RAMGraphics: NVIDIA GeForce GTX 660 with 2 GB VRAM or AMD Radeon HD 7870, with 2 GB VRAM or better - See supported List" matches = re.match(r'OS: (.+)Processor: (.+)Memory: (.+)Graphics: (.+)', string) requirements = { 'Os': matches.group(1), 'Processor': matches.group(2), 'Memory': matches.group(3), 'Graphics': matches.group(4), } print(requirements)
The regex is a little inflexible though and I would advice just using this as a starting point.
See re.match