Marcos Santana
Marcos Santana

Reputation: 951

Update values of a list of dictionaries in python

I have a CSV file that looks like this:

Martin;Sailor;-0.24
Joseph_4;Sailor;-0.12
Alex;Teacher;-0.23
Maria;Teacher;-0.57

My objective is to create a list with dictionaries for each job.

For example:

list_of_jobs = [{'Job' : Sailor, 'People' : ['Martin', 'Joseph']}
                 {'Job' : Teacher, 'People' : ['Alex', 'Maria']}
] 

I did create the dictionaries but I can't figure out how to update the value of list_of_jobs['People']

Can anybody help me?

Upvotes: 12

Views: 62389

Answers (3)

If you have a list of dictionary like this:

list_of_jobs = [
  {'Job' : 'Sailor', 'People' : ['Martin', 'Joseph']},
  {'Job' : 'Teacher', 'People' : ['Alex', 'Maria']}
]

You can access the dictionary by index.

list_of_jobs[0]

Output:
{'Job' : 'Sailor', 'People' : ['Martin', 'Joseph']}

If you want to access 'People' attribute of the first dictionary, you can do it like this:

list_of_jobs[0]['People']

Output:
['Martin', 'Joseph']

If you want to modify the value of that list of people, you can use append() to add an item or pop() to remove an item from the list.

list_of_jobs[0]['People'].append('Andrew')
list_of_jobs[0]['People'].pop(1)

Now, list_of_jobs will have this state:

[
  {'Job' : 'Sailor', 'People' : ['Martin', 'Andrew']},
  {'Job' : 'Teacher', 'People' : ['Alex', 'Maria']}
]

Upvotes: 11

Paul Panzer
Paul Panzer

Reputation: 53029

Your data structure is not ideal for the job; consider using a different one and then changing to yours in the very end:

data = "Martin;Sailor;-0.24 Joseph_4;Sailor;-0.12 Alex;Teacher;-0.23 Maria;Teacher;-0.57"
data = [r.split()[-1] for r in data.split(';')]
# data = ['Martin', 'Sailor', 'Joseph_4', 'Sailor', 'Alex', 'Teacher', 'Maria', 'Teacher', '-0.57']

# for the moment use one dict keyed with jobs for easy updating
out = {}
for name, job in zip(data[::2], data[1::2]):
    out.setdefault(job, []).append(name)
# out = {'Sailor': ['Martin', 'Joseph_4'], 'Teacher': ['Alex', 'Maria']}

# in the very end, convert to desired output format
out = [{'Job': job, 'People': people} for job, people in out.items()]
# out = [{'Job': 'Sailor', 'People': ['Martin', 'Joseph_4']}, {'Job': 'Teacher', 'People': ['Alex', 'Maria']}]

Upvotes: 2

xudesheng
xudesheng

Reputation: 1102

job_dict={}
job_dict['Sailor']=['Martin','Joseph']
job_dict['Teacher']=['Alex','Maria']

if you want to add "Marcos" as a Sailor, you can:

(job_dict['Sailor']).append('Marcos')

Upvotes: 6

Related Questions