Martin
Martin

Reputation: 4330

Python: Map list of two-entry-dicts to dict with first entry as key and second as value

I have something like this:

[{'date': 1, 'value':5}, {'date':2,'value':3}, ...]

and want to map the values this two keys to this:

{1:5, 2:3, ...}

How can I do this in a nice way?

Upvotes: 2

Views: 142

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

>>> lis = [{'date': 1, 'value':5}, {'date':2,'value':3}]
>>> {x['date']:x['value'] for x in lis}
{1: 5, 2: 3}

Upvotes: 7

Jon Clements
Jon Clements

Reputation: 142216

You could also do: The following Python code will extract the dictionary values:

dict(map(lambda L: L.values(), lst))

Upvotes: 0

Simeon Visser
Simeon Visser

Reputation: 122506

For Python 2:

>>> lis = [{'date': 1, 'value':5}, {'date':2,'value':3}]
>>> result = dict((x['date'], x['value']) for x in lis)
{1: 5, 2: 3}

For Python 3:

See Ashwini's answer.

Upvotes: 4

Related Questions