0

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[''].

5
  • This is not JSON, it's a dictionary. I'm removing the tag. Commented Oct 6, 2017 at 16:16
  • copy to a new dict Commented Oct 6, 2017 at 16:18
  • { k[6:-2] if k[:6]=="root['" else k :v for k,v in d.items() } where d is your old dictionary Commented Oct 6, 2017 at 16:25
  • @bulbus It's a bit complicated to read, but should work Commented Oct 6, 2017 at 16:27
  • posted as an answer to explain. Commented Oct 6, 2017 at 16:33

3 Answers 3

2

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'}}    
Sign up to request clarification or add additional context in comments.

1 Comment

This was exactly the solution I was looking for ;)
1

If your key all have type 'root[*]', you can use :

newkey = oldkey.replace("['"," ").replace("']","").split()[1]

3 Comments

Or just oldkey.replace("root['", '').replace("']", '')
@Phước Hữu Lưu That works great, simple, efficient, I like this kind of comment ;)
@Rawing it's also necessary to replace("']","")
1
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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.