简体   繁体   中英

Updating a set value in a dictionary for non existing key resulting in TypeError

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?

Well in Python, if you do something like

variable = {}

Then It's damn sure a dictionary by default

print(type(variable)) # <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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM