【问题标题】:Replacing a specific key in a nested dictionary without affecting other keys替换嵌套字典中的特定键而不影响其他键
【发布时间】:2020-05-27 14:42:58
【问题描述】:

正在处理查找和替换示例音乐词典的不正确键的特定功能,但我无法找到正确的代码来执行此操作。

my_dict = {
    1: {
        "Artist": "Pat Metheny",
        "Album": {"Offramp": {"Year": "1982"},
                  "First Cicrle": {"Year": "1985"}}
    },
    2: {
        "Artist": "William Ackerman",
        "Album": {"Imaginary Roads": {"Year": "1986"},
                  "Passage": {"Year": "1979"}}
    },
    3: {
        "Artist": "John Coltrane",
        "Album": {"A Love Supreme": {"Year": "1960"},
                  "Ballads": {"Year": "1966"}}
    }
}

add2dict = {}

def fix_case(x):
    x = ("".join([a if a.isupper() else b for a, b in zip(x, x.title())]))
    return x


def repl(rep):
    index = int(rep[0])
    for d, g in my_dict[int(rep[0])].items():
        if rep[1] in g:
            print('found it')
            print(my_dict[int(rep[0])]['Artist'])
            my_dict[int(rep[0])]['Artist'] = rep[2]
            print(my_dict)
        elif rep[1] in my_dict[index]['Album'].keys(): #check 'Album' keys for rep[1]
            print('found it in ', my_dict[index]['Album'])

            for alb, year in my_dict[index]['Album'].items():
                if alb == rep[1]:
                    my_dict[index]['Album'] = rep[1][year]

            print(my_dict)

        elif rep[1] in my_dict[index]['Year']:
            print('found it')
            my_dict[int(rep[0])]['Year'] = rep[2]

            print(my_dict[1])

        return


ndx2 = 1

keys = []
while True:

    def printData():
        for d, g in my_dict.items():
            print(f'ID: {d}')
            print('Artist:', g['Artist'])
            print("Albums:")
            for album, metadata in g['Album'].items():
                year = metadata['Year']
                print(f'-{album} ({year})')
            print()


    ndx2 = 1
    choice = int(input("1:Add an entry:\n2:Replace an entry\n3:quit or <ENTER>\n:"))
    if choice == int(1):
        Add_dbase = input('Add an entry: ')
    elif choice == int(2):
        printData()
        dbase_repl = input('Enter ID followed by \'/\' and \'old word\'/\'replace word\'')
        repl_keys = dbase_repl.split("/")
        print(my_dict[int(repl_keys[0])].items())
        repl(repl_keys)
        printData()
        break
    elif choice == int(3) or "":
        print("Nothing entered. Bye.")
        break
    else:
        break

在我的函数 def repl(rep) 中,处理更改专辑键的情况。我将 Artist 索引、拼写错误的键和正确的键分别传递为 'rep[0]'、rep[1]、rep[2]。在第一个 elif 块中,我可以缩小正确的键范围,但找不到正确的代码来更改它而不影响其他专辑键。例如,专辑“First Cicrle”拼写错误,我想将其更改为“First Circle”。我尝试使用 .replace、.update、.pop 和许多组合,但我没有只更改键名。请问有什么想法吗?谢谢!

【问题讨论】:

  • 您是否希望保持字典键的顺序?
  • 不要将专辑名称用作字典键。这样做需要您在检索专辑之前已经知道专辑的名称。将相册改为字典列表,每个都有一个name 键。
  • @Vishakha Lall,我还不担心订购。现在只需要能够替换专辑名称就足够了。
  • @kindall专辑标题已经在“专辑”键的列表中。如果有一个例子你的意思是什么?非常感谢。
  • @cpsharp 您需要根据关键字搜索更改键名吗?例如:查找:First Cicrle 并替换为First Circle,其中两个都是变量?

标签: python dictionary replace nested key


【解决方案1】:

您需要检查每个键和字典值以找到特定的短语。 然后根据更改的键值更新字典数据。replace 列表包含:[artist_id, old_key, new_key]

data = {
    1: {
        "Artist": "Pat Metheny",
        "Album": {"Offramp": {"Year": "1982"},
                  "First Cicrle": {"Year": "1985"}}
    },
    2: {
        "Artist": "William Ackerman",
        "Album": {"Imaginary Roads": {"Year": "1986"},
                  "Passage": {"Year": "1979"}}
    },
    3: {
        "Artist": "John Coltrane",
        "Album": {"A Love Supreme": {"Year": "1960"},
                  "Ballads": {"Year": "1966"}}
    }
}


replace = [1, 'First Cicrle', 'First Circle']

for k, v in data.items():
    if k == replace[0]:
        out = {}
        for key, value in data.get(replace[0]).items():
            if key == replace[1]:
                out[replace[2]] = value
            else:
                if isinstance(value, dict):
                    value3 = {}
                    for key2, value2 in value.items():
                        if key2 == replace[1]:
                            value3[replace[2]] = value2
                        else:
                            value3[key2] = value2
                    out[key] = value3
                else:
                    out[key] = value
        data[k] = out

输出:

{1: {'Artist': 'Pat Metheny', 'Album': {'Offramp': {'Year': '1982'}, 'First Circle': {'Year': '1985'}}}, 2: {'Artist': 'William Ackerman', 'Album': {'Imaginary Roads': {'Year': '1986'}, 'Passage': {'Year': '1979'}}}, 3: {'Artist': 'John Coltrane', 'Album': {'A Love Supreme': {'Year': '1960'}, 'Ballads': {'Year': '1966'}}}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 2016-04-14
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多