Home > Enterprise >  Zip list of dictionaries
Zip list of dictionaries

Time:09-22

Is there a way to zip a list of dictionaries by value?

For example:

d = [{'a': 1, 'b': 2}, {'a': 3, 'b': 5}]
list(zip(*d))
>>> [('a', 'a'), ('b', 'b')]

We can zip a dictionary by key as any other list of tuples, but I wanted the following result:

[(1, 3), (2, 5)]

Is this achievable using zip? Thanks in advance for any help you can provide.

CodePudding user response:

You can map the list of dicts to dict.values for zipping:

list(zip(*map(dict.values, d)))

CodePudding user response:

list(zip(*(dic.values() for dic in d)))

Gives:

[(1, 3), (2, 5)]

Documentation reference.

EDIT:

If you actually wanted [(1, 2), (3, 5)], that is just the keys of an iterable of dictionaries as tuples, then this is how:

[tuple(dic.values()) for dic in d]

But that is not what is commonly referred to as "zipping".

  • Related