使用Google People API查询联系人时如何同时获取姓名与电话号码
问题原因
你混淆了Google People API的请求参数规则和Python字典的取值规则:
- 调用
people().connections().list()时传入personFields='names,phoneNumbers'是正确写法,作用是告诉API需要返回这两个字段的数据,调用成功后返回的每个person字典对象中会同时存在names和phoneNumbers两个独立的顶级键。 - 你尝试用
person.get('names,phoneNumbers', [])取值属于错误写法:dict.get()方法的第一个参数是单个键名,传入逗号拼接的字段名相当于查找字典中是否存在名为names,phoneNumbers的键,这个键不存在,因此会一直返回默认的空列表。
正确写法
如果需要同时获取两个字段的内容,分别取值即可,示例如下:
for person in connections: # 分别取两个字段的值 names = person.get('names', []) phone_numbers = person.get('phoneNumbers', []) # 可根据需要整理为统一数据结构,比如存为字典 contact_info = { "names": names, "phoneNumbers": phone_numbers }
内容的提问来源于stack exchange,提问作者lord_nimon
相关产品推荐
相关产品推荐

