Reputation: 393
I'm posting this question after not finding the answer in the many existing issues related to this topic.
I have a dictionary similar to this one:
foo = {'a': [(1, 0.5), (2, 0.3)], 'b': [(3, 0.4), (4, 0.1)]}
and would like to access the items of the nested tupels, in order to create the following dictionary out of it:
foo = {'a': [1, 2], 'b': [3, 4]}
How do I go about doing this, preferably in a pythonic way?
Upvotes: 1
Views: 87
Reputation: 78650
I think these two solutions are easiest to read:
>>> from operator import itemgetter
>>> {k:map(itemgetter(0), foo[k]) for k in foo}
{'a': [1, 2], 'b': [3, 4]}
or import-less:
>>> {k:[x[0] for x in foo[k]] for k in foo}
{'a': [1, 2], 'b': [3, 4]}
Upvotes: 1
Reputation: 10951
You can do it with defaultdict
from collections
module:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d = defaultdict(list)
>>> for k in foo:
for v in foo[k]:
d[k].append(v[0])
>>> d
defaultdict(<class 'list'>, {'a': [1, 2], 'b': [3, 4]})
>>> d['a']
[1, 2]
Upvotes: 0
Reputation: 7179
{k:list(zip(x,y)[0]) for k,(x,y) in foo.iteritems()}
This gives:
{'a': [1, 2], 'b': [3, 4]}
Upvotes: 0
Reputation: 31662
Using dict comprehension
:
In [214]: {key:list(map(lambda x: x[0], foo[key])) for key in foo}
Out[214]: {'a': [1, 2], 'b': [3, 4]}
Upvotes: 0
Reputation: 2768
what about?
{x: map(lambda z: z[0], y) for x, y in foo.iteritems()}
Upvotes: 0