2

I have a dictionary in a list like:

my_list = [{'Name':'John','Age':'50','Job':'NIL'},{'Name':'Sara','Age':'70','Job':'NIL'}]

I want to change the value of the key Job in the list based on the parameter that whether their age is above or below 60, like if the age is below 60, the job value is changed to 1 and if the age is above 60 the job value is changed to 0. This is what out I am expecting:

my_list = [{'Name':'John','Age':'50','Job':'1'},{'Name':'Sara','Age':'70','Job':'0'}]
jpp
  • 159,742
  • 34
  • 281
  • 339
Faisal Afzal
  • 255
  • 1
  • 11

2 Answers2

4

You can do this by simply iterating over your list of dictionaries:

for dictionary in my_list:
    dictionary['Job'] = '0' if int(dictionary['Age']) > 60 else '1'

This results in:

>>> my_list
[{'Name': 'John', 'Age': '50', 'Job': '1'}, {'Name': 'Sara', 'Age': '70', 'Job': '0'}]
JakobHeltzig
  • 327
  • 2
  • 10
1

If you are happy using a 3rd party library, you can use Pandas:

import pandas as pd

df = pd.DataFrame(my_list)
df['Job'] = df['Age'].astype(int).le(60).astype(int).astype(str)

res = df.to_dict(orient='records')

[{'Age': '50', 'Job': '1', 'Name': 'John'},
 {'Age': '70', 'Job': '0', 'Name': 'Sara'}]

There are specific reasons why this is preferable. You are using vectorised operations on Boolean arrays rather than a ternary statement in a loop. For big data workflows, this should be time and memory efficient.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • 2
    This seems a bit overblown to me for such a simple problem. – kalehmann Oct 04 '18 at 12:06
  • @kalehmann, I wouldn't say so. There are specific reasons why this is preferable. You are using vectorised operations on Boolean arrays rather than a ternary statement in a loop. I know which I prefer and, indeed, which solution will work better in big data workflows. – jpp Oct 04 '18 at 12:07
  • 2
    I see your point and think I would agree with you for a really large list. But given the information in the question I still think this is not worth using a third party library like pandas and your other answer using list comprehension fits the problem more. – kalehmann Oct 04 '18 at 12:11
  • 1
    this actually runs better because my dataset is gigantic – Faisal Afzal Oct 04 '18 at 12:12
  • 1
    Okay, now I agree with you @jpp :) – kalehmann Oct 04 '18 at 12:16
  • @jpp Can you reference me something to read more on how to use it for more such manipulation – Faisal Afzal Oct 04 '18 at 12:41
  • The [tutorials mentioned in the docs](http://pandas.pydata.org/pandas-docs/stable/tutorials.html) are a good starting point. – jpp Oct 04 '18 at 12:43