Reputation: 2542
How to replace a key string extracting data from it using regex with Python, example :
{"root['toto']": {'new_value': 'abcdef', 'old_value': 'ghijk'}}
I'd like to replace root['toto']
with something easier to read, like toto
and my object might have several key like this, that I'd like to extract inside root['']
.
Upvotes: 0
Views: 2126
Reputation: 46759
You could use the following regular expression:
mydict = {
"root['toto']": {'new_value': 'abcdef', 'old_value': 'ghijk'},
"test['aaa']": {'new_value': 'abcdef', 'old_value': 'ghijk'},
"root['bb']": {'new_value': 'abcdef', 'old_value': 'ghijk'},
"ccc": {'new_value': 'abcdef', 'old_value': 'ghijk'}
}
for key, value in mydict.items():
new_key = re.sub(r"(\w+\[')(\w+)('\])", r"\2", key)
if new_key != key:
mydict[new_key] = mydict.pop(key) # Remove the old entry and add the entry back with new key
print mydict
Giving you an updated mydict
containing:
{'aaa': {'new_value': 'abcdef', 'old_value': 'ghijk'},
'bb': {'new_value': 'abcdef', 'old_value': 'ghijk'},
'toto': {'new_value': 'abcdef', 'old_value': 'ghijk'},
'ccc': {'new_value': 'abcdef', 'old_value': 'ghijk'}}
Upvotes: 2
Reputation: 2327
d={ k[6:-2] if k[:6]=="root['" else k :v for k,v in d.items() }
where d is your dictionary object
example
d={"root['abc']":2,'3':4}
d={ k[6:-2] if k[:6]=="root['" else k :v for k,v in d.items() }
print(d)
output
{'abc': 2, '3': 4}
explanation
we use dictionary comprehension to create a new dictionary.
breaking down the line:-
{ #Start dictionary construction
k[6:-2] if k[:6]=="root['" else k # this is our new key
: # key value separator
v #Keep the same value as the old one.
for k,v in d.items() #Do this for all key,values in my old dictionary.
} #End dictionary construction
without using dict comprehension
d={"root['abc']":2,'3':4} #d is our old dict
nd={} #nd is new dict
for k,v in d.items(): #iterating over each key,value k,v
nk= k[6:-2] if k[:6]=="root['" else k #nk is our new key
nd[nk]=v #setting nk:v in nd
print(nd) #print final dict
output
{'abc': 2, '3': 4}
Upvotes: 1
Reputation:
If your key all have type 'root[*]', you can use :
newkey = oldkey.replace("['"," ").replace("']","").split()[1]
Upvotes: 1