I have a problem adding a value to a set which is a value in a dictionary. I have to use sets as values not list or anything else. I have seen this thread but it does not full ansver me.
from collections import defaultdict
datoteka = open("vzorec.list","rt")
slovar = defaultdict(set)
for vrstica in datoteka:
seznam = vrstica.split("\t")
naslov = seznam[0]
beseda = seznam[len(seznam)-1]
beseda = beseda.strip()
naslov2 = ""
for crka in naslov:
if crka == "(":
break
else:
naslov2 = naslov2 + crka
naslov = naslov2.lstrip('"')
if naslov not in slovar:
slovar[naslov] = set(beseda)
elif naslov in slovar:
slovar[naslov] = slovar[naslov].add(beseda)
print(slovar)
I get an error that a string type does not have an add function. But why does python not understand that I want to have sets as values. I even used the defaultdict
There is no add() , append() , or insert() method you can use to add an item to a dictionary in Python. Instead, you add an item to a dictionary by inserting a new index key into the dictionary, then assigning it a particular value.
We can add / append new key-value pairs to a dictionary using update() function and [] operator. We can also append new values to existing values for a key or replace the values of existing keys using the same subscript operator and update() function.
You just want:
slovar[naslov].add(beseda)
instead of:
if naslov not in slovar:
slovar[naslov] = set(beseda) # set of characters in beseda string ???
elif naslov in slovar:
slovar[naslov] = slovar[naslov].add(beseda) # add to the set, returns None ???
This works because with a defaultdict
, if the key isn't present, it adds an empty set as the value to that particular key and returns it empty set. So, the first time around, slovar[naslov]
returns an empty set which you then .add(beseda)
.
Python understands fine :). You have a bug in your code.
set.add
mutates the set and returns None
, so you've discarded your set and set the key to None
. You just want to do slovar[naslov].add(beseda)
whether naslov
is or isn't in the set, and not care about the return value.
I don't see how a string would be getting in there, so if that doesn't solve your issue, you need to paste a full traceback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With