0

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.

3 Answers3

0

use extend() to append a list to another list. And use Dictionary[element] to get the contents of the matching key.

if element in value:
    value.extend(Dictionary[element])
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

"the key to which value belongs" is literally just key, but going a step further, Dictionary[key] is value. So:

value.append(Dictionary[element])

Although, you'll also want to replace .append() with .extend() in order to get your desired output.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
-1
#define the dictionary
Dictionary = {
    "a": ["x", "z"],
    "b": ["y", "w"],
    "c": ["a", "q"],
    "d": ["w", "a"]
    }

#get all the keys from the dictionary
listOfKeys = list(Dictionary.keys())

for key, value in Dictionary.items():
    items_to_add = []
    for letter in value:
        if letter in listOfKeys:
            items_to_add.append(letter) # Store off the keys whose value we need to append
    for item in items_to_add:           # Run this in a second loop so that we're not modifying a list we're currently iterating through
        for new_item in Dictionary[item]:
            if new_item not in value:   # Only add each item if it's not already in the target list
                value.append(new_item)

# Test that we've done it right
expected = {
    "a": ["x", "z"],
    "b": ["y", "w"],
    "c": ["a", "q", "x", "z"],
    "d": ["w", "a", "x", "z"]}

# Does not throw an Exception because at this point, Dictionary and expected are identical
assert Dictionary == expected 
Chance
  • 440
  • 2
  • 6
  • Welcome to SO! Check out the [tour]. It would help a lot to add a written description to explain how this code answers the question. See [answer] if you want more tips. – wjandrea Feb 18 '21 at 21:46
  • The second inner loop is unnecessary. – wjandrea Feb 18 '21 at 21:46
  • Thanks a lot for the responses @Chance @Barmar @wjandrea, that works perfectly. One thing I forgot to mention is that I also don't want to add any values from `a` that are already in the target key. So if "d" : ["w", "a", "x"] I want it to end up as d : ["w", "a", "x" "z"] again instead of having `x` two times. My bad that I forgot to mention it but I thought it better to ask here again instead of opening a new question. – crimsontides097 Feb 18 '21 at 21:48
  • Updated to include the new requirement – Chance Feb 18 '21 at 21:51
  • @crimsontides097 That is actually a different question, but it's already been asked: [Add only unique values to a list in python](https://stackoverflow.com/q/42334197/4518341) – wjandrea Feb 18 '21 at 21:53