Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Add elements to set value in a dictionary

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

like image 284
HRIbar Avatar asked Aug 21 '12 12:08

HRIbar


People also ask

Can you add to a dictionary value in Python?

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.

How do you add a value to an existing key in a dictionary?

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.


2 Answers

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

like image 159
mgilson Avatar answered Oct 08 '22 20:10

mgilson


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.

like image 41
Julian Avatar answered Oct 08 '22 19:10

Julian