Changing original dictionaries
You can simply iterate over your list of dictionaries and the calculations. Make sure to round the result since you want an integer:
>>> list_of_dicts = [{'id': 'a', 'population': '20', 'area': '10'},
{'id': 'a', 'population': '20', 'area': '10'}]
>>>
>>> for d in list_of_dicts:
d['pop_density'] = int(d['population']) // int(d['area']) # round result by using //
>>> list_of_dicts
[{'pop_density': 2, 'population': '20', 'id': 'a', 'area': '10'}, {'pop_density': 2, 'population': '20', 'id': 'a', 'area': '10'}]
>>>
Creating new dictionaries
Python 3
If you want a new list of dictionaries, you can use a list comprehension:
>>> list_of_dicts = [{'id': 'a', 'population': '20', 'area': '10'},
{'id': 'a', 'population': '20', 'area': '10'}]
>>>
>>> [{'pop_densitiy': int(d['population']) // int(d['area']), **d} for d in list_of_dicts]
[{'area': '10', 'population': '20', 'id': 'a', 'pop_densitiy': 2}, {'area': '10', 'population': '20', 'id': 'a', 'pop_densitiy': 2}]
>>>
Python 2
Note the above uses the dictionary unpacking operator that is only available in python 3. If using Python 2, you'll need to use the dict
constructor:
>>> list_of_dicts = [{'id': 'a', 'population': '20', 'area': '10'},
{'id': 'a', 'population': '20', 'area': '10'}]
>>> [dict(d, pop_densitiy=int(d['population']) // int(d['area'])) for d in list_of_dicts]
[{'pop_densitiy': 2, 'population': '20', 'id': 'a', 'area': '10'}, {'pop_densitiy': 2, 'population': '20', 'id': 'a', 'area': '10'}]
>>>