我很抱歉,如果这已经得到了答复(我看了,没找到任何东西.)请告诉我,我会立即删除.
我正在编写一个程序来进行API调用,该调用根据调用返回多个不同长度的列表(例如,facebook API调用.输入人名和返回的图片列表,每张图片都列出了谁喜欢“每张照片.我想存储这些”喜欢“列表.
#Import urllib for API request
import urllib.request
import urllib.parse
#First I have a function that takes two arguments, first and last name
#Function will return a list of all photos the person has been tagged in facebook
def id_list_generator(first,last):
#Please note I don't actually know facebook API, this part wil not be reproducible
pic_id_request = urllib.request.open('www.facebook.com/pics/id/term={first}+{last}[person]')
pic_id_list = pic_id_request.read()
for i in pic_id_list:
id_list.append(i)
return(id_list)
#Now, for each ID of a picture, I will generate a list of people who "liked" that picture.
#This is where I have trouble. I don't know how to store these list of lists.
for i in id_list:
pic_list = urllib.request.open('www.facebook.com/pics/id/like/term={i}[likes]')
print pic_list
这将为该人被标记的每张图片打印多个“喜欢”列表:
foo, bar
bar, baz
baz, foo, qux
norf
我真的不知道如何诚实地存放这些.
我想在追加后使用看起来像这样的列表:
foo = [["foo", "bar"], ["bar","baz"],["baz","foo","qux"],["norf"]]
但实际上我不确定在这种情况下使用什么类型的存储.我想过使用字典的字典,但我不知道密钥是否可以迭代.我觉得有一个简单的答案我错过了.
最佳答案 好吧,你可以有一个词典列表:
这是一个例子:
facebook_likes = [{
"first_name": "John",
"last_name": "Smith",
"image_link": "link",
"likes": ["foo"]
}, {
"first_name": "John",
"last_name": "Doe",
"image_link": "link",
"likes": ["foo", "bar"]
}]
for like in facebook_likes:
print like
print like["likes"]
print like["likes"][0]
您还应该查看JSON对象.
它是API调用后获得的标准响应对象之一.
幸运的是,将Python dict转换为JSON对象非常简单,反之亦然.