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}
>Solution :
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}