简体   繁体   中英

How to replace key string in dictionary with Python and regex?

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

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'}}    

如果您的密钥都具有'root [*]'类型,则可以使用:

newkey = oldkey.replace("['"," ").replace("']","").split()[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}

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