Pythonic Way To Replace Dict Keys and/or Values

非 Y 不嫁゛ 提交于 2021-01-28 06:01:53

问题


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

For example, if I have this:

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
}

回答1:


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)



回答2:


In straight-forward way:

result = {}
for k,v in data.items():
    if '{{var_' in k:     # if `{{var..}}` placeholder is in key
        result[variables[k[6:-2]]] = v
    elif '{{var_' in v:   # if `{{var..}}` placeholder is in value
        result[k] = variables[v[6:-2]]
    else:
        result[k] = v

print(result)

The output:

{'user_id': 10, 'orders_count': 4, 'name': 'bob'}



回答3:


This is a pretty manual algorithm, but here goes:

for key, value in data.iteritems():
    if "var" in str(key):
        #iterate through "variables" to find the match
    elif "var" in str(value):
        #iterate through "variables" to find the match

    #populate "data" with the key value pair

This will work, but it's kind of messy if you can't guarantee uniqueness, especially in the case where a key needs to be replaced.



来源:https://stackoverflow.com/questions/46718629/pythonic-way-to-replace-dict-keys-and-or-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!