Hacker News new | past | comments | ask | show | jobs | submit login

re: "Your defaultdict approach and the dict.get with a default specified is not really equivalent. In the defaultdict case when you encounter a non existing key it adds a new entry with that key into the dict. i.e. your dict will start growing."

europa - The dictionary is only modified if you are using a method to modify it. When you are just passively querying it, it's not impacted.

   class defaultdict(dict):

      def __init__(self, default=None):
          dict.__init__(self)
          self.default = default

      def __getitem__(self, key):
          try:
              return dict.__getitem__(self, key)
          except KeyError:
              return self.default

   mdict=defaultdict(0)
   mdict['gordon']=10
   mdict['tim']=20
   print mdict['gordon']   
   print mdict['tim']
   print mdict['george']
   print mdict

   10
   20
   0
   {'tim': 20, 'gordon': 10}



You are right about your implementation. I was thinking about the Pythons collections.defaultdict

from collections import defaultdict s = 'mississippi' d = defaultdict(int) for k in s: d[k] += 1 d.items()

[('i', 4), ('p', 2), ('s', 4), ('m', 1)]


The difference here - is that you are actually assigning a value to the dictionary element. It's the assignment that's growing the dictionary, not the query.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: