使用嵌套字典替换字符串中的单词

时间:2019-07-09 05:12:14

标签: python

我正在尝试使用嵌套字典替换字符串中的单词,如果它包含键和value1,然后将其替换为字典的value2。

我已经创建了如下字典。

RenameEnums = { 'DPST': {'Name': 'ENHANCEMENT', 'Rename': 
                      'D_ENHANCEMENT'},
                'BASE': {'Name': 'Cursor', 'Rename': 'CBase'}}

def replace(string,dict):
    for key, val in dictionary.items():
    line = line.replace(key, val)
    return line

我不知道如何访问嵌套字典的第二个值。 预期输出:

情况:1 应替换,因为它既包含键又包含广告值1

String: DPST ENHANCEMENT is not easy
Replaced: D_ENHANCEMENT is not east

情况:2 不应替换,因为字符串中不存在密钥。

String: DSL is very easy in respect with ENHANCEMENT

1 个答案:

答案 0 :(得分:0)

  

我不知道如何访问嵌套字典的第二个值。

在您的代码示例中,您可以以val['Name']的形式访问嵌套值。

在for循环for key, val in dictionary.items()中,val实际上是另一本不能直接在string.replace()函数中使用的字典。

尝试一下:

RenameEnums = { 'DPST': {'Name': 'ENHANCEMENT', 'Rename': 
                  'D_ENHANCEMENT'},
            'BASE': {'Name': 'Cursor', 'Rename': 'CBase'}}

def replace(string, dict):
  for key, val in dict.items():
    # Check if key is present in the string
    if string.find(key) > -1:
      # Replace all occurrences of 'Name' with 'Rename'
      string = string.replace(val['Name'], val['Rename'])
  return string

line1 = "DPST ENHANCEMENT is not easy"
line1 = replace(line1, RenameEnums)