I have a dictionary, whose keys map to a list of values. I am trying to create a function, that outputs a dict whose key only maps to one value. In the dictionary, if the key maps to a list of elements, the first element of the list is the correct value, and should be persisted and other elements of the list should be mapped to this element in the dictionary. But if that first element as previously been linked to another value, it should be linked to that
Example
Input:d = {
'apples': ['fruit1', 'fruit2'],
'orange': ['fruit3', 'round'],
'grape':['fruit2', 'fruit5'],
'mango': ['round']
}
Expected Output:
o = {'apples': 'fruit1', # since fruit1 was the first element
'fruit2': 'fruit1', # fruit2 should link to the first element (fruit1)
'orange': 'fruit3', # first element persisted
'round': 'fruit3', # second element, round, links to the first, fruit3
'grape': 'fruit1', # should keep first element fruit2, but since fruit2 linked to fruit1 earlier, link to fruit1
'fruit5': 'fruit1', # since fruit2 links to fruit1
'mango': 'fruit3' # since round links to fruit 3
}
In this example, "apples" links to fruit1 and fruit2 in the input. "fruit1" should be the value that persists (bc its the first element). But since "apples" links to "fruit1" and "fruit2", "fruit2" should also be linked to "fruit1".
Then later, when "grape" maps to "fruit2", "grape" should be re-linked to "fruit1", since "fruit2" got linked to "fruit1" earlier. Similarly, "mango" in the output maps to "fruit3" because "round" was linked to "fruit3" before (for orange)
Key property: None of the values of the dict are present in the keys
My Code:
new_d = {}
relinked_items = {}
for key, values in d.items():
if len(values) == 1:
value = values[0]
if key not in new_d:
# if value has been relinked before, link to that
if value in relinked_items:
new_d[key] = relinked_items[value]
# hasnt been relinked
else:
new_d[key] = value
continue
target_value = values[0]
# link key to target value
new_d[key] = target_value
for value in values[1:]:
if target_value in relinked_items:
new_d[value] = relinked_items[target_value]
# hasnt been relinked
else:
new_d[value] = target_value
My output
{'apples': 'fruit1', # correct
'fruit2': 'fruit1', # correct
'fruit5': 'fruit2', # wrong. fruit2 maps to fruit1
'grape': 'fruit2', # wrong fruit2 maps to fruit1
'mango': 'round', # wrong. round maps to fruit3
'orange': 'fruit3', # correct
'round': 'fruit3'} # correct
Anyone on advice on how to get the correct output? I maintain a dict in my code captures values of the dict that have been relinked, so I can always route the current value to that. Although, seems to be a bug somewhere