+2 votes
in Programming Languages by (9.6k points)

I want to convert a dictionary into two lists. One list should contain all keys, and the other should have all values.

E.g.

t= {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

to

[1, 2, 3, 4, 5]  and 

['a', 'b', 'c', 'd', 'e']

Is there any Python function for this operation?

1 Answer

+1 vote
by (42.1k points)

There are a couple of ways to convert a Python dictionary into lists.

Using keys() and values()

  • keys() returns all dictionary keys, and you can cast the returned values into a list.
  • values() returns all dictionary values, and you can cast the returned values into a list.

Example:

>>> t= {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> l1 = list(t.keys())
>>> l1
['a', 'b', 'c', 'd', 'e']
>>> l2 = list(t.values())
>>> l2
[1, 2, 3, 4, 5]


Using items()

  • items() returns a list of tuples. The tuple contains a (key, value) pair. You can apply unzip() to get the list of keys and values.
Example:
>>> t= {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> l1,l2=list(map(list, zip(*t.items())))
>>> l1
['a', 'b', 'c', 'd', 'e']
>>> l2
[1, 2, 3, 4, 5]
 
...