Google 日历中的与会者并不总是按相同的顺序排列

Attendees in Google Calendar not always in the same order

所以我刚刚开始使用 google 日历 api,到目前为止我取得了很好的效果。我在 events 字典中添加了与会者的姓名和电子邮件,就像这样

events = { 

              # other stuff here and then this

              'items': [

                   # lots of stuff here, followed by

                  'attendees': [
                     {
                        'email': email1,
                        'displayName': name1
                     },
                     {
                        'email': email2,
                        'displayName': name2
                     },
                  ], 

                  ###

                ]
            }

添加它们没问题,但是当我访问它们时,我无法保证它们的顺序。我以为我可以像这样访问电子邮件

for event in events['items']:
    print "email1 = " + str(event['attendees'][0]['email'])
    print "email2 = " + str(event['attendees'][1]['email'])

我可以。而且我了解到 python always have their order preserved 中的列表,这很方便,因为我想使用列表的索引访问列表中的字典。但我了解到,有时 0 索引指的是 email1,有时它指的是 email2。为什么不一致?它是 google 日历 api 固有的,还是在 python 列表中放宽了顺序保留假设的字典对象?还是我还缺少其他东西?

因此,正如@Colonel 三十二指出的那样,虽然列表保留顺序,但 google return 数据如何进入列表可能与提交给他们的顺序不同。如果您想依靠该顺序来检索与会者,那么这种与与会者的顺序不一致会很不方便

for event in events['items']:
    print "email1 = " + str(event['attendees'][0]['email'])
    print "email2 = " + str(event['attendees'][1]['email'])

此外,google 日历 api 可写入的字段很少。然而,可写的是 comments。因此,我在该字段中添加了一个值以使与会者可识别。像这样

'attendees': [
            {
                'email': agent_email,
                'displayName': agent_name,
                'comment': 'agent'
            },
            {
                'email': event_attendee_email,
                'displayName': event_attendee_name,
                'comment': 'client'
            },

使用 comment 作为标识符帮助我通过简单的 if 语句检索每个与会者的 emaildisplayName

for i in range(len(event['attendees'])):
        if event['attendees'][i]['comment'] == 'client':
            event['attendees'][i]['displayName'] = event_attendee_name
            event['attendees'][i]['email'] = event_attendee_email

现在,google 日历 api 以与我添加他们的顺序不同的顺序将我的与会者提交回给我并不重要。我现在可以检索与会者,以便我可以更改他们。问题已解决。