Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
Marcos Santana Avatar asked Mar 28 '17 04:03

Marcos Santana


People also ask

Can dictionary values be updated in Python?

Python Dictionary update() The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.

How do you update multiple values in a dictionary?

By using the dictionary. update() function, we can easily append the multiple values in the existing dictionary. In Python, the dictionary. update() method will help the user to update the dictionary elements or if it is not present in the dictionary then it will insert the key-value pair.

How do you update an element in a list in Python?

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method.


1 Answers

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']}
]
like image 159
Mgs M Rizqi Fadhlurrahman Avatar answered Oct 25 '22 00:10

Mgs M Rizqi Fadhlurrahman