Questions tagged [defaultdict]

A subclass of Python's dict class that allows to specify a default factory to use for missing keys.

This tag would be applicable to Python questions related with the instantiation, filling and subclassing of the collections.defaultdict class.

defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class.

collections.defaultdict([default_factory[, ...]])

The first argument provides the initial value for the default_factory attribute; it defaults to None. Commonly used default_factories are int, list or dict.

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

this is equivalent to:

>>> d = dict()
>>> for k, v in s:
...     d.setdefault(k, []).append(v)
...

http://docs.python.org/library/collections.html

647 questions
798
votes
15 answers

Collections.defaultdict difference with normal dict

I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs >>> from collections import defaultdict >>> s = 'mississippi' >>> d = defaultdict(int) >>> for k…
Lanston
  • 11,354
  • 8
  • 32
  • 37
215
votes
12 answers

Nested defaultdict of defaultdict

Is there a way to make a defaultdict also be the default for the defaultdict? (i.e. infinite-level recursive defaultdict?) I want to be able to do: x = defaultdict(...stuff...) x[0][1][0] {} So, I can do x = defaultdict(defaultdict), but that's…
Corley Brigman
  • 11,633
  • 5
  • 33
  • 40
140
votes
3 answers

How to convert defaultdict to dict?

How can I convert a defaultdict number_to_letter defaultdict(, {'2': ['a'], '3': ['b'], '1': ['b', 'a']}) to be a common dict? {'2': ['a'], '3': ['b'], '1': ['b', 'a']}
user2988464
  • 3,251
  • 6
  • 21
  • 25
124
votes
6 answers

Is there a clever way to pass the key to defaultdict's default_factory?

A class has a constructor which takes one parameter: class C(object): def __init__(self, v): self.v = v ... Somewhere in the code, it is useful for values in a dict to know their keys. I want to use a defaultdict with the key…
Benjamin Nitlehoo
  • 1,611
  • 2
  • 13
  • 12
113
votes
11 answers

`if key in dict` vs. `try/except` - which is more readable idiom?

I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case: I want to build dictionary A from dictionary B. If a specific key does not exist in B, then do nothing and continue…
LeeMobile
  • 3,775
  • 6
  • 31
  • 32
95
votes
5 answers

Python defaultdict and lambda

In someone else's code I read the following two lines: x = defaultdict(lambda: 0) y = defaultdict(lambda: defaultdict(lambda: 0)) As the argument of defaultdict is a default factory, I think the first line means that when I call x[k] for a…
user740006
  • 1,759
  • 4
  • 20
  • 30
88
votes
3 answers

defaultdict with default value 1?

I am new to python, and i read some code snippet from some place. It's an implementation of counting sort. The code is as below: from collections import defaultdict def sort_colors(A): ht = {} # a hash map ht =…
chancyWu
  • 14,073
  • 11
  • 62
  • 81
75
votes
9 answers

Format string unused named arguments

Let's say I have: action = '{bond}, {james} {bond}'.format(bond='bond', james='james') this wil output: 'bond, james bond' Next we have: action = '{bond}, {james} {bond}'.format(bond='bond') this will output: KeyError: 'james' Is there some…
nelsonvarela
  • 2,310
  • 7
  • 27
  • 43
59
votes
10 answers

Can't pickle defaultdict

I have a defaultdict that looks like this: dict1 = defaultdict(lambda: defaultdict(int)) The problem is, I can't pickle it using cPickle. One of the solution that I found here is to use module-level function instead of a lambda. My question is,…
Fynn Mahoney
  • 699
  • 1
  • 7
  • 10
55
votes
1 answer

python defaultdict: 0 vs. int and [] vs list

Is there any difference between passing int and lambda: 0 as arguments? Or between list and lambda: []? It looks like they do the same thing: from collections import defaultdict dint1 = defaultdict(lambda: 0) dint2 = defaultdict(int) dlist1 =…
beardc
  • 20,283
  • 17
  • 76
  • 94
40
votes
3 answers

Exposing `defaultdict` as a regular `dict`

I am using defaultdict(set) to populate an internal mapping in a very large data structure. After it's populated, the whole structure (including the mapping) is exposed to the client code. At that point, I don't want anyone modifying the mapping.…
max
  • 49,282
  • 56
  • 208
  • 355
34
votes
1 answer

TypeError: multiple bases have instance lay-out conflict

I wanted to create a class out of two: collections.OrderedDict and collections.DefaultDict. So that I can get an ordered dictionary and have a default value for non existing keys being accessed. Whats are some ways to do this? My solution was to…
user6046760
  • 454
  • 1
  • 4
  • 6
34
votes
4 answers

Sorting a defaultdict by value in python

I have a data-structure which is something like this: The population of three cities for different year are as follows. Name 1990 2000 2010 A 10 20 30 B 20 30 10 C 30 10 20 I am using a defaultdict to store the data. from…
imsc
  • 7,492
  • 7
  • 47
  • 69
30
votes
6 answers

How to initialize defaultdict with keys?

I have a dictionary of lists, and it should be initialized with default keys. I guess, the code below is not good (I mean, it works, but I don't feel that it is written in the pythonic way): d = {'a' : [], 'b' : [], 'c' : []} So I want to use…
Amir
  • 1,926
  • 3
  • 23
  • 40
27
votes
3 answers

defaultdict : first argument must be callable or None

I ran the following code : from collections import defaultdict lst = list(range(0,5)) d = defaultdict(lst) and I got this error : TypeError: first argument must be callable or None Please help
Arcyno
  • 4,153
  • 3
  • 34
  • 52
1
2 3
43 44