Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zip the values from a dictionary [duplicate]

Tags:

python

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.

like image 215
Luca Avatar asked Nov 17 '16 15:11

Luca


People also ask

Does zip remove duplicates?

Answer. If the list passed to the zip() function contains duplicate data, the duplicate created as part of the list comprehension will be treated as an update to the dictionary and change the value associated with the key. No error will be reported.

Can dictionary store duplicate values?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python. But we can have a similar effect as keeping duplicate keys in dictionary.

Can you zip dictionaries?

zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.

Can you zip dictionary in Python?

To create a dictionary from two sequences, use the dict() and zip() method. The dict(zip(keys, values)) needs the one-time global lookup each for dict and zip.


1 Answers

You can do the following:

zip(*x.values())

Explanation:

  • 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.
like image 195
Ozgur Vatansever Avatar answered Oct 05 '22 23:10

Ozgur Vatansever