Luca Luca - 1 year ago 63
Python Question

zip the values from a dictionary

I have a dictionary in python 2.7 that has the following structure:

x = {
'1': ['a', 'b', 'c'],
'2': ['d', 'e', 'f']

The length of the value list is always the same and I would like to basically zip the value lists with corresponding values. So, in this case it will create three new lists as:

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

I know I can write an awful looking loop to do this but I was wondering if there is a more pythonic way to do this. I need to preserve the order.

Answer Source

You can do the following:



  • x.values() returns [['a', 'b', 'c'], ['d', 'e', 'f']] (order may change so you might need to sort x first.)
  • zip([a, b], [c, d]) returns [[a, c], [b, d]]
  • To expand x.values() into arguments to zip, prepend * to it.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download