user6773543
user6773543

Reputation:

How to insert to a list of dictionaries values in a specific key

I have a list of dictionaries which is like this

mylist = [ {'Var1': 'one', 'Var2': 'two', 'Var3': '0'}, {'Var1': 'one', 'Var2': 'two', 'Var3': '0'} ]

What if i want to get the index for mylist[0]['Var1'] ?? I need to get the index of it not change it manually. Im iterrating through my list with a for loop and i need to know in what index it belongs

Upvotes: 0

Views: 63

Answers (3)

Tshiteej
Tshiteej

Reputation: 121

The value of the dictionary fields can be directly overwritten.

Example: If you want to change 'Var3' key's value at the first dictionary, it would be like mylist[0]['Var3'] = 'something'

Upvotes: 1

Andrew Growney
Andrew Growney

Reputation: 11

If you just want to work with the first dictionary in 'mylist', you can access it at:

mylist[0]

So adjusting its 'Var3's value would be

mylist[0]['Var3'] = 'something_new'

Upvotes: 1

Raamyy
Raamyy

Reputation: 580

1- You should get your first dictionary from the list by mylist[0].

2- and then nest it with accessing your desired key ['Var3'].

So the command will be: mylist[0]['Var3'] = value

Upvotes: 2

Related Questions