Pythonic方式替换Dict键和/或值

时间:2017-10-12 20:48:03

标签: python dictionary substitution

我正在寻找一个高效的'迭代字典的方法,并替换以术语“var'”开头的任何键或值。

例如,如果我有这个:

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

我有这个变量值的字典:

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

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

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

3 个答案:

答案 0 :(得分:1)

直截了当地说:

library(tidyverse)

df_long <- df_wide %>% 
  gather(key=Category, value=Measurement, Cat1:Cat3_err, factor_key = TRUE) %>%
  separate(Category, into = c("Category", "Type")) %>%
  mutate(Type = ifelse(is.na(Type), "Measurement", "Error")) %>%
  spread(Type, Measurement) %>%
  select(Reading, Category, Measurement, Error, Sample)
df_long
   Reading Category Measurement       Error Sample
1        1     Cat1   0.8453114 0.074961215    X14
2        1     Cat2   4.5962112 0.059012908    X14
3        1     Cat3   5.4100838 0.076049726    X14
4        2     Cat1   4.5956145 0.016215603    X23
5        2     Cat2   1.7768868 0.040258838    X23
6        2     Cat3   1.9597101 0.027356213    X23
7        3     Cat1   1.6204584 0.057760820    X11
8        3     Cat2   4.9478913 0.054855327    X11
9        3     Cat3   2.9670444 0.004276482    X11
10       4     Cat1   0.1831593 0.038415489    X10
11       4     Cat2   2.5716471 0.024932980    X10
12       4     Cat3   8.5517659 0.015378512    X10

输出:

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)

答案 1 :(得分:1)

因为您将它视为文本模板语言(如果您是,那么为什么不使它成为string.format(** variable)兼容语法?)使用文本替换:

import ast
import re

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

print(data2)

答案 2 :(得分:0)

这是一个非常手动的算法,但这里有:

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

这样可行,但如果你不能保证唯一性,那就太麻烦了,特别是在需要更换的情况下。