samsamara
samsamara

Reputation: 4750

How is this "add" method used on a dictionary?

I'm new to python and can't seem to find any reference for an add() method for dictionary data structure in python. But I was debugging a python code and found the following code.

token = {}
try:
    token[t].add(offset)
except KeyError:
    token[t] = set([offset])

Below are the set of imports used in the code.

from ConfigParser import SafeConfigParser
import copy
import json
import math
from optparse import OptionParser
import os
import signal
import string
import sys

From where does that add() method comes for the dictionary?

Upvotes: 0

Views: 70

Answers (2)

Jayanth Koushik
Jayanth Koushik

Reputation: 9894

The add method that you see is not for the dictionary, but rather for an item in the dictionary (a set)

token[t] accesses the item mapped by t

and

token[t].add calls add on the item mapped by t

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

It doesn't. It's on the set stored as a value, not on the dict itself.

Upvotes: 2

Related Questions