用Python方式替换Dict键和/或值 [英] Pythonic Way To Replace Dict Keys and/or Values

查看:65
本文介绍了用Python方式替换Dict键和/或值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种有效"的方法来遍历字典,并替换以"var"开头的任何键或值.

I'm looking for an 'efficient' way to iterate through a dictionary, and replace any key or value that starts with the term 'var'.

例如,如果我有这个:

data = {
    "user_id": "{{var_user_id}}",
    "name": "bob",
    "{{var_key_name}}": 4
}

我有这个变量值的字典:

and I have this dict of variable values:

variables = {
    "user_id": 10,
    "key_name": "orders_count"
}

然后,我希望我的最终数据字典看起来像这样:

Then I'd like my final data dict to look like this:

data = {
    "user_id": 10,
    "name": "bob",
    "orders_count": 4
}

推荐答案

由于您将其像文本模板语言一样对待(如果可以,为什么不使其成为string.format(** variable)兼容语法?)使用文本替换:

Since you're treating it like a text template language (and if you are, then why not make it string.format(**variable) compatible syntax?) use text replacement:

import ast
import re

text = re.sub('{{var_(.*?)}}', lambda m: variables[m.groups()[0]], str(data))    
data2 = ast.literal_eval(text)

print(data2)

这篇关于用Python方式替换Dict键和/或值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆