1

I am trying to add new key pair value to to a dictionary:

What my code outputs at the moment is:

dict_items([((2, 2), 2)])

What I actually want:

{(0, 0): 0}, {(0, 1): 2}, {(0, 2): 3}, {(1, 0): 1}, {(1, 1): 1}, {(1, 2): 2}, {(2, 0): 5}, {(2, 1): 3}, {(2, 2): 2}

Can anyone explain how to update my dictionary with the new key value pairs? I tried using update function call but got the following error:

TypeError: unhashable type: 'set'

Any help is highly appreciated!

    distanceList = []
    trainingset = [5, 6, 10]
    testset = [5,7,8]

    for i in trainingset:
        for j in testset:
            distance = abs(i-j)
            values = dict()
            values[trainingset.index(i),testset.index(j)] = distance
            # values.update({{trainingset.index(i),testset.index(j)}:distace})
            distanceList.append(distance)

    print(distanceList)
    print(values.items())
  • Possible dupe, take a look here: https://stackoverflow.com/questions/1024847/add-new-keys-to-a-dictionary and https://stackoverflow.com/questions/41063744/how-to-update-the-value-of-a-key-in-a-dictionary-in-python – sniperd Jun 19 '18 at 17:38
  • You are resetting `values` in every loop. Initialize it before you start looping. – Leo Jun 19 '18 at 17:42
  • @Leo Thank you very much for that – Anirudh Anil Kumar Jun 19 '18 at 17:44

1 Answers1

0

The error of "unhashable type: set" indicates that you're trying to use a set object as a dictionary key, and sets cannot be keys of dictionaries.

And while I don't think you're intentionally trying to create a set or use it as a dictionary key, that's what this line is doing:

values.update({{trainingset.index(i),testset.index(j)}:distace})

(The inner curly braces, without a colon inside will create a set object).

If you just want a tuple, as your example output suggests, try:

values.update({(trainingset.index(i),testset.index(j)):distace})

Which should work, provided you make a few other small changes (e.g. distace -> distance, hoisting your creation of values outside your loops).

jedwards
  • 29,432
  • 3
  • 65
  • 92