Редактировать словари внутри списка очень просто.
Сначала вам нужно получить словарь, вызвав индекс списка, в котором он находится.
Затем вы можете отредактировать словарькак обычно.
Взгляните на приведенные ниже примеры.Я написал несколько циклов for для чтения или редактирования словарей в списке.
list_of_dicts = [{"name":"Mike","age":30}, {"name":"Dave","age":22}, {"name":"Amber","age":24}]
for ndex, item in enumerate(list_of_dicts):
# This will print the index number and dictionary at that index.
print(ndex, item)
for item in list_of_dicts:
# This will print each persons name and age of each dict in the list.
print("The persons name is {} and they are {} years old!".format(item["name"], item["age"]))
for item in list_of_dicts:
# this will update the age of each person by 1 year.
item["age"] += 1
print(list_of_dicts)
# This will change Daves name to Mark.
list_of_dicts[1]["name"] = "Mark"
print(list_of_dicts[1])
Если вы запустите приведенный выше скрипт, вы должны получить следующие результаты в консоли:
0 {'name': 'Mike', 'age': 30}
1 {'name': 'Dave', 'age': 22}
2 {'name': 'Amber', 'age': 24}
The persons name is Mike and they are 30 years old!
The persons name is Dave and they are 22 years old!
The persons name is Amber and they are 24 years old!
[{'name': 'Mike', 'age': 31}, {'name': 'Dave', 'age': 23}, {'name': 'Amber', 'age': 25}]
{'name': 'Mark', 'age': 23}