I have some kind of verbose logic that I'd like to compact down with some comprehensions.
Essentially, I have a dict object that I'm reading from which has 16 values in it that I'm concerned with. I'm getting the keys that I want with the following comprehension:
["I%d" % (i,) for i in range(16)]
The source dictionary kind of looks like this:
{ "I0": [0,1,5,2], "I1": [1,3,5,2], "I2": [5,9,10,1], ... }
I'd like to essentially map this dictionary to be something like this:
[
{ "I0": 0, "I1": 1, "I2": 5, ... }
{ "I0": 1, "I1": 3, "I2": 9, ... }
...
]
How can I map things with list and dictionary comprehensions to transform my source dict into my destination list of dictionaries?
We can add a filter to the iterable to a list comprehension to create a dictionary only for particular data based on condition. Filtering means adding values to dictionary-based on conditions.
The only difference between Generator Comprehension and List Comprehension is that the former uses parentheses.
Its syntax is the same as List Comprehension. It returns a generator object. A dict comprehension, in contrast, to list and set comprehensions, needs two expressions separated with a colon. The expression can also be tuple in List comprehension and Set comprehension.
Essentially, the only difference between this and the list comprehension is the use of curly braces to contain the comprehension and the placement of x before the colon to indicate that this represents the key. This can be then also be used to create a dictionary based on an already existing list.
This is a fully functional solution that can be applied on arbitrary size.
d = { "I0": [0,1,5,2], "I1": [1,3,5,2], "I2": [5,9,10,1]}
map(dict, zip(*map(lambda (k, v): map(lambda vv: (k, vv), v), d.iteritems())))
to elaborate: (I'm using ipython
and the underscore _
means the previous output)
In [1]: d = {'I0': [0, 1, 5, 2], 'I1': [1, 3, 5, 2], 'I2': [5, 9, 10, 1]}
In [2]: map(lambda (k, v): map(lambda vv: (k, vv), v), _.iteritems())
Out[2]:
[[('I1', 1), ('I1', 3), ('I1', 5), ('I1', 2)],
[('I0', 0), ('I0', 1), ('I0', 5), ('I0', 2)],
[('I2', 5), ('I2', 9), ('I2', 10), ('I2', 1)]]
In [3]: zip(*_)
Out[3]:
[(('I1', 1), ('I0', 0), ('I2', 5)),
(('I1', 3), ('I0', 1), ('I2', 9)),
(('I1', 5), ('I0', 5), ('I2', 10)),
(('I1', 2), ('I0', 2), ('I2', 1))]
In [4]: map(dict, _)
Out[4]:
[{'I0': 0, 'I1': 1, 'I2': 5},
{'I0': 1, 'I1': 3, 'I2': 9},
{'I0': 5, 'I1': 5, 'I2': 10},
{'I0': 2, 'I1': 2, 'I2': 1}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With