splitting a dictionary in python into keys and values

Viewed 60956

How can I take a dictionary and split it into two lists, one of keys, one of values. For example take:

{'name': 'Han Solo', 'firstname': 'Han', 'lastname': 'Solo', 'age': 37, 'score': 100, 'yrclass': 10}

and split it into:

['name', 'firstname', 'lastname', 'age', 'score', 'yrclass']
# and
['Han Solo', 'Han', 'Solo', 36, 100, 10]

Any ideas guys?

2 Answers

as a compliment to @Wolph answer,

its important to say that using zip may be much slower!


Added split_with_tuple - as split returns view objects as of python3

In [1]: def split(d):
   ...:     return d.keys(), d.values()
   ...:
   ...:

In [2]: def split_with_tuple(d):
   ...:     return tuple(d.keys()), tuple(d.values())
   ...:
   ...:

In [3]: def split_with_zip(d):
   ...:     return zip(*d.items())
   ...:
   ...:

In [4]: d = {i:str(i) for i in range(10000)}

In [5]: %timeit split(d)
265 ns ± 12.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [6]: %timeit split_with_tuple(d)
151 µs ± 772 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [7]: %timeit split_with_zip(d)
950 µs ± 15.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Related