组织列表的动态列表

时间:2016-01-05 00:38:46

标签: python list python-2.7 dictionary

我很抱歉,如果这已经得到了解答(我看了,但没有找到任何东西。)请告诉我,我会立即删除。

我正在编写一个程序进行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"]]

但实际上我不确定在这种情况下使用什么类型的存储。我想过使用字典的字典,但我不知道密钥是否可以迭代。我觉得有一个简单的答案我错过了。

2 个答案:

答案 0 :(得分:2)

好吧,你可以有一个词典列表:

以下是一个例子:

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对象非常简单,反之亦然。

答案 1 :(得分:0)

如果您只想按每个列表中的第一个元素进行排序,Python会默认为2D列表执行此操作。请参阅此主题:Python sort() first element of list

相关问题