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

Time:05-07

I have a dict with two strings "Candy-one" and "Candy-two" as the key and Capacity as the key pair. I wish to replace the strings "Candy-one" and "Candy-two" with the Brand-Name which has the same candies in the same spots "Candy-one" and "Candy-two"

This is what I tried

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))

this is my output

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

Its as if nothing is happening This is the output I want

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

CodePudding user response:

Using a double loop is not efficient (quadratic complexity).

Here is how I would solve it:

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)

output:

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

CodePudding user response:

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}
 

Or your corrected attempt:

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}

CodePudding user response:

key, being a tuple, does not have a pop method, suggesting you never actually try to change f (maybe because you never call Brand).

Plus the stuff @quamrana indicated.

  • Related