2017-08-17 45 views
1

我想要定義一個類,它將從包含多個字典的列表中製作標記列表(請參閱下文),但是當我嘗試使用時,會得到以下回溯。我不確定我做錯了什麼。任何意見,將不勝感激!使用複雜列表定義類時出現錯誤

File "file.py", line 415, in <module> 
    p = Photo(data) 
    File "file.py", line 395, in __init__ 
    for d in p_d["photo"]["tags"]["tag"]["_content"]: 
TypeError: list indices must be integers or slices, not str 

當前代碼:

class Photo : 

    def __init__(self,p_d) : 
     self.tags = [] 
     for d in p_d["photo"]["tags"]["tag"]["_content"]: 
      self.tags.append(d) 
     return 

p = Photo(data) 
print(p) 

「數據」 的內容看起來像 「照片選詞」 中this post。下面是與標籤部分的例子:

 u'media':u'photo', 
    u'tags':{ 
     u'tag':[ 
      { 
       u'machine_tag':False, 
       u'_content':u'aerialview', 
       u'author':u'[email protected]', 
       u'raw':u'Aerial View', 
       u'authorname':u'Patrick Foto ;)', 
       u'id':u'59579247-33334692904-8319' 
      }, 
      { 
       u'machine_tag':False, 
       u'_content':u'buildingexterior', 
       u'author':u'[email protected]', 
       u'raw':u'Building Exterior', 
       u'authorname':u'Patrick Foto ;)', 
       u'id':u'59579247-33334692904-1727027' 
      }, 
      { 
       u'machine_tag':False, 
       u'_content':u'businessfinanceandindustry', 
       u'author':u'[email protected]', 
       u'raw':u'Business Finance and Industry', 
       u'authorname':u'Patrick Foto ;)', 
       u'id':u'59579247-33334692904-263370815' 
      }, 

回答

1

顯然,p_d["photo"]["tags"]["tag"]是一個列表,你可以不採取項目['_content']在列表中。

你可以做

for adict in p_d["photo"]["tags"]["tag"]: 
    self.tags.append(adict["_content"]) 
+0

我看到現在。如果我只想得到['_content']位,我應該怎麼處理? – BothanSpy

+0

問題是,列表中的每個項目都有一個「_content」。你想要哪一個?如果你只想要第一個,你可以做'[0] ['_ content']'。如果你想要所有這些,你需要添加一個for循環。 – Gribouillis

+0

我想將它們全部返回到列表中。編輯:這是我在當前循環中試圖做的。 – BothanSpy

相關問題