Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner for updating a value in a list of dictionaries - Python

Tags:

python

I have a list of dictionaries like so:

l = [{"integer":"1"},{"integer":"2"},{"integer":"3"},{"integer":"4"}]

I would like to do something similar to the following so that each of the numbers which are the value pair for the "integer" key are returned as integers:

l = [{"integer":"1"},{"integer":"2"},{"integer":"3"},{"integer":"4"}]
r = map(lambda x: x["integer"]=int(x["integer"]), l)
print r 
#[{"integer":1},{"integer":2},{"integer":3},{"integer":4}]

But this causes an error:

SyntaxError: lambda cannot contain assignment

Does anyone know of a clean way to do this in python? Preferably a oneliner using map or something similar?

like image 443
Justin Gardner Avatar asked Jan 02 '23 21:01

Justin Gardner


1 Answers

Use a list comprehension comprehension

You will iterate through the dictionaries in the list and have them returned as x, then insert a new dictionary with your desired key and the integer value of the return within a new list

r = [{'integer': int(x['integer'])} for x in l]
like image 90
Nick Dima Avatar answered Jan 26 '23 11:01

Nick Dima