Home > Software design >  Updating a set value in a dictionary for non existing key resulting in TypeError
Updating a set value in a dictionary for non existing key resulting in TypeError

Time:10-26

There is a variable x = {1:{1,2,3,4}}
What I understand by this is that in the dict x the key 1 is mapped to the set {1,2,3,4}
Now when I do x.get(1,{}).update([4,5]) x becomes {1: {1, 2, 3, 4, 5}}

But when I do x.get(2,{}).update([1,2]) I get an error:

TypeError: cannot convert dictionary update sequence element #0 to a sequence

What could be the reason for this?

CodePudding user response:

Well in Python, if you do something like

variable = {}

Then it is damn sure a dictionary by default

print(type(variable))

Output:

<class 'dict'>

In order to create an empty set, you have to do something like

variable = set()

That's the reason for that error message

Anyway, the get method does not create a new key in a dictionary

I think you may have been looking for the .setdefault method

x = {
   1: {1,2,3,4}
}
x.setdefault(1, set()).update([4,5])
x.setdefault(2, set()).update([4,5])
print(x)

Outputs:

{1: {1, 2, 3, 4, 5}, 2: {4, 5}}

Here, the .setdefault method assigns a new key to the dictionary if it's not there, and gives an empty set as a value, and proceeds to return it

Which is later updated by the update method

If the given key exists in the dictionary, then it returns its value

Tell me if it's not working

  • Related