【问题标题】:Replacing all keys and values in nested python dictionary with new values用新值替换嵌套python字典中的所有键和值
【发布时间】:2015-12-08 12:46:48
【问题描述】:

假设我在 python 中有一个嵌套的dict:

a[1][2] = 4
a[1][3][3] = 5

我还有另一个直截了当的非嵌套字典,如下所示:

{
    1 : "Kansas City",
    2 : "Toledo",
    3 : "Houston",
    4 : "Champaign",
    5 : "Seattle"
}

如何将第一个字典中与第二个字典中的键匹配的所有键和值替换为第二个字典的对应值,以便输出如下所示:

a["Kansas City"]["Toledo"] = "Champaign"
a["Kansas City"]["Houston"]["Houston"] = "Seattle

【问题讨论】:

标签: python dictionary data-structures


【解决方案1】:

我采用了递归方法,如果数据的值是字典 - 尝试替换键和值。否则它将数据视为单个值并尝试对其进行转换。

replace_dict 是指出如何转换值的字典,data 是当前值。

def replace_key_val(data, replace_dict):
    if type(data)== dict:
        return {replace_dict[k] : replace_key_val(v, replace_dict) for k,v in data.iteritems()}
    return replace_dict[data]

【讨论】:

    【解决方案2】:

    字符串替换? 并使用 ast 将字符串转换为 dict... ??

    a={}
    a[1] = { 2 : 4 }
    a[2] = { 3 : { 3 : 4 }}
    
    replacement = {
        1 : "Kansas City",
        2 : "Toledo",
        3 : "Houston",
        4 : "Champaign",
        5 : "Seattle"}
    
    
    aStr = str(a)
    for key,value in replacement.iteritems() :
        aStr = aStr.replace( str(key), "'%s'"%value )
    
    import ast
    newA = ast.literal_eval(aStr)
    print newA
    

    【讨论】:

      猜你喜欢
      • 2022-10-13
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      • 1970-01-01
      • 2019-01-25
      • 2018-04-19
      相关资源
      最近更新 更多