I am a beginner in Python and I have what seems like a simple issue with my code but I can't figure it out. I have a dictionary with several keys, each of which contains a list of values, and I want to do the following: For each key, find if its name appears as a value in any other key, and if so, append its contents to that key as well.
I think it's easier to explain with an example. I have the following:
#define the dictionary
Dictionary = {
"a": ["x", "z"],
"b": ["y", "w"],
"c": ["a", "q"],
"d": ["w", "a"]
}
#get all the keys from the dictionary
listOfKeys = []
for key in Dictionary.keys():
listOfKeys.append(key)
#try to append the key values to any matches
for key, value in Dictionary.items():
for element in listOfKeys:
if element in value:
Dictionary[?].append(Dictionary[element])
Obviously, in the last line, instead of "?", I should have the key to which value
belongs to, but I am not sure how to get it. After doing that, I expect the dictionary to look like this:
"a": ["x", "z"],
"b": ["y", "w"],
"c": ["a", "q", "x", "z"],
"d": ["w", "a", "x", "z"]
In other words, the contents of key a
are added to keys c
and d
, because those are the keys in which a
appears as a value. Ideally I would only append the values if they are not already in that key as well, but I think I can sort that part out myself. I found one solution online (not sure if I can link it here) but it seems to only work if the values are a string, and not a list as in my case.
Hopefully I have explained this clearly enough to be understandable.