Get python dictionary from string containing key value pairs

I have a python string in the format:

str = "name: srek age :24 description: blah blah" 

is there any way to convert it to a dictionary that looks like

 {'name': 'srek', 'age': '24', 'description': 'blah blah'} 

where each record is a pair (key, value) taken from a string. I tried breaking a string into a list

 str.split() 

and then manually delete : by checking each tag name, adding to the dictionary. The disadvantage of this method is: this method is unpleasant, I need to manually delete : for each pair, and if there are several words "value" in the line (for example, blah blah for description ), each word will be a separate entry in the list, which is undesirable. Is there any Pythonic way to get a dictionary (using python 2.7)?

+6
source share
3 answers
 >>> r = "name: srek age :24 description: blah blah" >>> import re >>> regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)") >>> d = dict(regex.findall(r)) >>> d {'age': '24', 'name': 'srek', 'description': 'blah blah'} 

Explanation:

 \b # Start at a word boundary (\w+) # Match and capture a single word (1+ alnum characters) \s*:\s* # Match a colon, optionally surrounded by whitespace ([^:]*) # Match any number of non-colon characters (?= # Make sure that we stop when the following can be matched: \s+\w+\s*: # the next dictionary key | # or $ # the end of the string ) # End of lookahead 
+30
source

without re :

 r = "name: srek age :24 description: blah blah cat: dog stack:overflow" lis=r.split(':') dic={} try : for i,x in enumerate(reversed(lis)): i+=1 slast=lis[-(i+1)] slast=slast.split() dic[slast[-1]]=x lis[-(i+1)]=" ".join(slast[:-1]) except IndexError:pass print(dic) {'age': '24', 'description': 'blah blah', 'stack': 'overflow', 'name': 'srek', 'cat': 'dog'} 
+2
source

Other Aswini program options that display the dictionary in its original order

 import os import shutil mystr = "name: srek age :24 description: blah blah cat: dog stack:overflow" mlist = mystr.split(':') dict = {} list1 = [] list2 = [] try: for i,x in enumerate(reversed(mlist)): i = i + 1 slast = mlist[-(i+1)] cut = slast.split() cut2 = cut[-1] list1.insert(i,cut2) list2.insert(i,x) dict.update({cut2:x}) mlist[-(i+1)] = " ".join(cut[0:-1]) except: pass rlist1 = list1[::-1] rlist2= list2[::-1] print zip(rlist1, rlist2) 

Exit

[('name', 'srek'), ('age', '24'), ('description', 'blah blah'), ('cat', 'dog'), ('stack', 'overflow')]

0
source

Source: https://habr.com/ru/post/914502/


All Articles