New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Overriding dictionary value under wrong key. #85656
Comments
I'm writing a function that combines two dictionaries called "baseProducts" and "variantProducts". def combineProductsByColor(baseProducts, variantProducts):
retDict = {}
for key, variant in variantProducts.items():
productKey = variant['parent'] + '_' + variant['color']
if productKey not in retDict:
retDict[productKey] = baseProducts[variant['parent']]
retDict[productKey]['variants'] = {}
retDict[productKey]['variants'][key] = variant
return retDict Now with my test data, baseProducts only contains one item in it. While variantProducts contain 4 items. When the first two loops happen it creates a new key, and adds the first and second variant under that key correctly (this was tested using ms code debugger) but when it looks at the 3rd item, it creates a new key, and adds the variant to that key, but it also overrides all the variants in the previous key, even if the variable productKey is the new key. And when the 4th item gets processed it again gets added to both. def combineProductsByColor(baseProducts, variantProducts):
retDict = {}
keys = list(variantProducts.keys())
for k in keys:
productKey = variantProducts[k]['parent'] + '_' + variantProducts[k]['color']
if productKey not in retDict:
retDict[productKey] = baseProducts[variantProducts[k]['parent']]
retDict[productKey]['variants'] = {}
retDict[productKey]['variants'][k] = variantProducts[k]
return retDict But the result was identical. Again following the whole procedure with ms code debugger. Now I do have an idea how to implement this in a different way, but I don't see and understand why the code I provided doesn't work. Because when the new key gets generated, its not the same as the old, but it still can change values under the old key. Here is what the data looks like before and after processing it. baseProducts: { variantProducts: { And last combined data: { |
This is expected behaviour. the assessment to retProduct[productKey] is not a copy. If those variants have the same parent and a different color you'll end up with a baseProduct where 'variants' refers to the same variant dict (and the second color seen will overwrite the value of 'variants') |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: