Skip to content

Instantly share code, notes, and snippets.

@nvbn
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nvbn/cf9a4a7a3a141402a7ff to your computer and use it in GitHub Desktop.
Save nvbn/cf9a4a7a3a141402a7ff to your computer and use it in GitHub Desktop.
python_collections_sucks.py
# python 3:
In [1]: a = {'x': 10, 'y': 50}
In [2]: b = {'a': 5, 'c': 12}
In [3]: a.keys() + b.keys()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-5b3174d08fb5> in <module>()
----> 1 a.keys() + b.keys()
TypeError: unsupported operand type(s) for +: 'dict_keys' and 'dict_keys'
In [4]: from functools import reduce
In [5]: import operator
In [6]: reduce(operator.add, [a.keys(), b.keys()])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-8129105009f4> in <module>()
----> 1 reduce(operator.add, [a.keys(), b.keys()])
TypeError: unsupported operand type(s) for +: 'dict_keys' and 'dict_keys'
In [7]: from itertools import chain
In [8]: list(chain.from_iterable([a.keys(), b.keys()]))
Out[8]: ['y', 'x', 'a', 'c']
# python 2
In [1]: a = {'x': 10, 'y': 50}
In [2]: b = {'a': 5, 'c': 12}
In [3]: a.keys() + b.keys()
Out[3]: ['y', 'x', 'a', 'c']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment