[英]Python: Add value into list inside dictionary
Trying to add a value into weekdays:[0]
from a variable called dow
. 尝试从名为dow
的变量向weekdays:[0]
添加值。
create_data = {"startDateTime":"2015-02-23T09:05:00-0600","endDateTime":"2015-02-23T10:05:00-0600","accessories":[],"customAttributes":[{"attributeId":"3","attributeValue":""},{"attributeId":"5","attributeValue":"Yes"}],"description":"Placeholder Description","invitees":[],"participants":[],"recurrenceRule":[{"type":"weekly","interval":2,"weekdays":[0],"repeatTerminationDate":"2015-05-24T09:50:00-0600"}],"resourceId":"15","resources":["15"],"title":"","userId":"26","startReminder":"","endReminder":""}
I'm getting confused between adding into a dictionary and a list. 我在添加字典和列表之间感到困惑。
Tried the following but it churns out the error below; 尝试了以下操作,但会清除以下错误;
create_data['recurrenceRule']['weekdays'] = dow
Below is the error. 下面是错误。
Traceback (most recent call last):
File "api.py", line 51, in <module>
create_data['recurrenceRule']['weekdays'] = dow
TypeError: list indices must be integers, not str
How do I access that value? 我如何获得该价值?
As value of create_data['recurrenceRule']
is list and list contains dictionary as item. 由于create_data['recurrenceRule']
值为列表,并且列表包含字典作为项。 So We have to get item from the list ie dictionary and add weekdays
key in it. 因此,我们必须从列表(即字典)中获取项目,并在其中添加weekdays
键。
create_data['recurrenceRule'][0]['weekdays'] = dow
create_data
is a dictionary, recurrenceRule
being one of its keys. create_data
是一个字典, recurrenceRule
是它的键之一。 Then, its value is a list: 然后,它的值是一个列表:
>>> create_data['recurrenceRule']
[{'repeatTerminationDate': '2015-05-24T09:50:00-0600', 'interval': 2, 'type': 'weekly', 'weekdays': 2}]
So to change weekdays
you firstly have to access to the first element in the list: 因此,要更改weekdays
您首先必须访问列表中的第一个元素:
create_data['recurrenceRule'][0]['weekdays']=dow
^^^
That's why you get this error: 这就是为什么出现此错误的原因:
create_data['recurrenceRule']['weekdays']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
Because you are trying to access to the index (0, 1, 2...) of a list with a string. 因为您尝试使用字符串访问列表的索引(0、1、2 ...)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.