简体   繁体   中英

How can I convert a string to dictionary in a manner where I have to extract key and value from same string

I need to convert string to dictionary in a manner for example

str1 = "00001000-0009efff : a 00100000-656b2fff : b"

Output what I require is

dict1 = {'a':['00001000','0009efff'], 'b':['00100000','656b2fff']}

Note: str1 can have many more such c , d , e with range.

You can do it with a regex:

import re

pattern = r'([\w\-]+) : ([\w\.]+)'
out = {m[1]: m[0].split('-') for m in re.findall(pattern, str1)}

Explanation of the regex:

  • match combination of alphanumeric characters and dashes [\w-]+
  • followed by a space, a colon and a space _:_
  • followed by a combination of alphanumeric characters and dot [\w\.]+

The groups are catching your relevant infos.

Assuming you only have a single key letter for each value

str1 = str1.replace(" : ", ":").split(" ")
output = {}
for _, s in enumerate(str1):
    output[s[-1]] = s[:-2].split("-")

This code will work in general

str1 = "00001000-0009efff : a 00100000-656b2fff : b"
needed_dictionary = dict()
split_string = str1.split()

for i in range(len(split_string)):
if split_string[i] == ":":
    needed_dictionary[split_string[i+1]]= split_string[i-1].split("-")
    
print(needed_dictionary)

But in Case the values or keys have "-" or ":" in them then this will fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM