![](/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.