0

I am a beginner at programing and python.

So I was interested in finding out the difference between a defaultdict and a normal {} dict.

See for example I made a defaultdict.

import collections
d = collections.defaultdict(list)
s = [('yellow', 1), ('blue', 2), ('yellow', 1), ('blue', 4), ('red', 1)]

for k, v in s:
if v not in d[k]: # if value not in list already
    d[k].append(v)

now when I return d I get something like this.

defaultdict(<class 'list'>, {'blue': [2, 4], 'red': [1], 'yellow': [1]})

So my question is 2 fold, What is the meaning of defaultdic and how is it different from normal dic. And How can I get rid of the defaultdict in front of the dictionary.. or essentially just change it to a normal dictionary.

Does it have to do with how I append the values to the dictionary.

Andre
  • 1,601
  • 6
  • 19
  • 19

1 Answers1

3

Just pass it through dict() function:

d = dict(d)

And for your second question: defaultdict is a factory, that creates dictionaries, that setup dictionary, with default values for non-existing keys. Instead of raising KeyError when you try to get key, that is not in dictionary, it creates dictionary with key you have tried, and value returned from function, that was an argument to defauldict, when you created one.

For more, see documentation: https://docs.python.org/2/library/collections.html#collections.defaultdict

m.wasowski
  • 6,329
  • 1
  • 23
  • 30
  • hey thanks for the great info ! But I seem to be getting a KeyError – Andre Oct 05 '14 at 02:36
  • @Ali We need to see your code if you want us to tell you where the error is. So either add this new code to your question (making sure that the indenting is correct), or even better, start a new question. – PM 2Ring Oct 05 '14 at 05:19