![](/img/trans.png)
[英]Regex - How to replace a word in a string with its entry in a python dictionary?
[英]How to replace key string in dictionary with Python and regex?
如何使用正則表達式替換Python中提取數據的鍵字符串,例如:
{"root['toto']": {'new_value': 'abcdef', 'old_value': 'ghijk'}}
我想用更容易閱讀的東西替換root['toto']
,例如toto
,我的對象可能有幾個這樣的鍵,我想在root['']
提取。
您可以使用以下正則表達式:
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
給您更新的mydict
包含:
{'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() }
其中d是您的字典對象
例
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)
產量
{'abc': 2, '3': 4}
說明
我們使用字典理解來創建新字典。
打破界限:
{ #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
不使用dict理解
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
產量
{'abc': 2, '3': 4}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.