Python | Dict

dict

Remove keys with empty value

Remove the empty string '' or the None value

1
2
3
4
5
6

In [24]: d
Out[24]: {'a': 'a', 'b': 'b', 'c': '', 'd': None}

In [25]: dict((k, v) for k, v in d.items() if v)
Out[25]: {'a': 'a', 'b': 'b'}

Find keys / items in common between 2 dict

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

>>> a = {'x': 1, 'y': 2, 'z': 3}
>>> b = {'x': 1, 'y': 2, 'z': 3, 'u': 1, 'v': 2, 'w': 2}

# 1). Keys in common
>>> a.keys() & b.keys()

# 2). Keys in b that not in a
>>> b.keys() - a.keys()

# 3). (key, value) pairs
>>> a.item() & b.item()

# 4). Make a new dictionary with certain keys removed
>>> c = {key: b[key] for key in b.keys() - {'x', 'y', 'z'}}

use zip

1
2
3
4
5
6
7

In [1]: a = [1, 2, 3]

In [2]: b = ['a', 'b', 'c']

In [3]: dict(zip(a, b))
Out[3]: {1: 'a', 2: 'b', 3: 'c'}

collections.defaultdict

“The standard dictionary includes the method setdefault()`` for retrieving a value and establishing a default if the value does not exist. By contrast,defaultdict` lets the caller specify the default(value to be returned) up front when the container is initialized.”

To Initialize

  1. Passing callable objects as its first argument(Required):

For example:

1
2
3

>>> d_int = defaultdict(int)
>>> d_list = defaultdict(list)
  1. kwargs as its second argument(Optional)

For example:

1
2
3
4
5
6
7
8
9

>>> d_int = defaultdict(int, a=10, b=12, c=13)
>>> d_int
defaultdict(<type 'int'>, {'a': 10, 'c': 13, 'b': 12})

>>> kwargs = {'a':10,'b':12,'c':13}
>>> d_int = defaultdict(int, **kwargs)
>>> d_int
defaultdict(<type 'int'>, {'a': 10, 'c': 13, 'b': 12})

How to?

As is a child class of standard dictionary, it can perform all the same functions.

But in case of passing an unknown key it returns the default value instead of error.

For example:

1
2
3
4
5
6
7

>>> d_int['a']
10
>>> d_int['d']
0
>>> d_int
defaultdict(<type 'int'>, {'a': 10, 'c': 13, 'b': 12, 'd': 0})

In case you want to change default value overwrite default_factory:

1
2
3
4
5
6
7
8
9
10
11
12

>>> d_int.default_factory = lambda: 1
>>> d_int['e']
1
>>> d_int
defaultdict(<function <lambda> at 0x7f34a0a91578>, {'a': 10, 'c': 13, 'b': 12, 'e': 1, 'd': 0})

# or

>>> def foo():
... return 2
>>> d_int.default_factory = foo

defaultdict Example

1
2
3
4
5
6
7
8
9
10
11

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

collections.OrderedDict

Return an instance of a dict subclass, supporting the usual dict methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

1
2
3
4
5
6
from collections import OrderedDict

d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
...

References:

  1. http://stackoverflow.com/questions/5900578/how-does-collections-defaultdict-work
  2. http://stackoverflow.com/questions/111234/what-is-a-callable-in-python
    3.