在保持键值 python 的同时通过比较更改字典的键名

Changing key name of a dictionary by comparing while keeping key value python

我有一个字典,其中有两个字符串“Candy-one”和“Candy-two”作为键,Capacity 作为键对。我希望用在相同位置“Candy-one”和“Candy-two”中具有相同糖果的品牌名称替换字符串“Candy-one”和“Candy-two”

这是我试过的

p = [['Brand-Name', 'Swap', ' Candy-one ', ' Candy-two ', 'Capacity'],
     ['Willywonker', 'Yes', 'bubblegum', 'mints', '7'],
     ['Mars-CO', 'Yes', 'chocolate', 'bubblegum', '1'],
     ['Nestle', 'Yes', 'bears', 'bubblegum', '2'],
     ['Uncle Jims', 'Yes', 'chocolate', 'bears', '5']] 

f = {('bubblegum', 'mints'): 4,
     ('chocolate', 'bubblegum'): 1,
     ('bears', 'bubblegum'): 2,
     ('chocolate', 'bears'): 2}

def Brand(f,p):
    i = 0
    while i < len(p)-1:
        i = i + 1
        for key in f:
            print(key[0])
            print(key[1])
            if key[0] == p[i][2] and key[1] == p[i][3]:
                f[p[i][0]] = key.pop(key)

    return f


print(brand(f,p))

这是我的输出

{('bubblegum', 'mints'): 4,
 ('chocolate', 'bubblegum'): 1,
 ('bears', 'bubblegum'): 2,
 ('chocolate', 'bears'): 2}

好像什么都没发生 这是我想要的输出

{'Willywonker': 4,
 'Mars-CO': 1,
 'Nestle': 2,
 'Uncle Jims': 2}

key,作为一个元组,没有 pop 方法,建议你永远不要真正尝试改变 f(可能是因为你从不调用 Brand) .

加上@quamrana 指出的内容。

def Brand(f,p):
    res={}
    i = 0
    while i < len(p)-1:
        for key in f:
            if key[0] == p[i+1][2] and key[1] == p[i+1][3]:
                res[p[i+1][0]] = f[key]
        i += 1
    return res

new_dict = Brand(f,p)
print(new_dict)
    
{'Willywonker': 4, 'Mars-CO': 1, 'Nestle': 2, 'Uncle Jims': 2}
 

或者您更正的尝试:

def Brand(f,p):
    res=f.copy()
    i = 0
    while i < len(p)-1:
        for key in f:
            if key[0] == p[i+1][2] and key[1] == p[i+1][3]:
                res[p[i+1][0]] = res.pop(key)
        i += 1
    return res 

updated_dict = Brand(f,p)
print(updated_dict)

{'Willywonker': 4, 'Mars-CO': 1, 'Nestle': 2, 'Uncle Jims': 2}

使用双循环效率不高(二次复杂度)。

以下是我的解决方法:

def Brand(f,p):
    # create a mapping dictionary
    d = {tuple(x[2:4]): x[0] for x in p[1:]}

    # output a new dictionary with replaced keys
    # or old key if a new one is not found
    return {d.get(k, k): v for k,v in f.items()}
    # or  if you want to drop in case of no match
    # return {d[k]: v for k,v in f.items() if k in d}

Brand(f,p)

输出:

{'Willywonker': 4,
 'Mars-CO': 1,
 'Nestle': 2,
 'Uncle Jims': 2}