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())
3

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.