2013-10-27 72 views
0

我正在編寫我的第一個Python程序,以使用其RESTful API在Atlassian On Demand中管理用戶。我調用users/search?username = API來檢索返回JSON的用戶列表。結果是一個複雜的字典類型的列表,看起來像這樣:從嵌套字典列表中刪除重複項

[ 
     { 
      "self": "http://www.example.com/jira/rest/api/2/user?username=fred", 
      "name": "fred", 
      "avatarUrls": { 
       "24x24": "http://www.example.com/jira/secure/useravatar?size=small&ownerId=fred", 
       "16x16": "http://www.example.com/jira/secure/useravatar?size=xsmall&ownerId=fred", 
       "32x32": "http://www.example.com/jira/secure/useravatar?size=medium&ownerId=fred", 
       "48x48": "http://www.example.com/jira/secure/useravatar?size=large&ownerId=fred" 
      }, 
      "displayName": "Fred F. User", 
      "active": false 
     }, 
     { 
      "self": "http://www.example.com/jira/rest/api/2/user?username=andrew", 
      "name": "andrew", 
      "avatarUrls": { 
       "24x24": "http://www.example.com/jira/secure/useravatar?size=small&ownerId=andrew", 
       "16x16": "http://www.example.com/jira/secure/useravatar?size=xsmall&ownerId=andrew", 
       "32x32": "http://www.example.com/jira/secure/useravatar?size=medium&ownerId=andrew", 
       "48x48": "http://www.example.com/jira/secure/useravatar?size=large&ownerId=andrew" 
      }, 
      "displayName": "Andrew Anderson", 
      "active": false 
     } 
    ] 

我打這個多次,因此得到重複的人在我的結果。我一直在搜索和閱讀,但無法弄清楚如何對此列表進行重複數據刪除。我想出瞭如何使用lambda函數對這個列表進行排序。我意識到我可以對列表進行排序,然後迭代和刪除重複項。我在想,必須有一個更優雅的解決方案。

謝謝!

回答

0

用戶名是唯一的,對吧?

是否必須是list?看起來像一個簡單的解決方案將是使其dictdict s代替。使用用戶名作爲密鑰,只有最新的版本纔會出現。

如果值已經被訂購,還有一個OrderedDict類型你可以看看:http://docs.python.org/2/library/collections.html#collections.OrderedDict

+0

必須多次調用RESTful接口才能獲取所有用戶,因此用戶名在組合列表中不是唯一的。現在,我使用自定義排序函數對列表進行排序,然後通過列表反向迭代,刪除重複項。似乎會有一個更簡單的解決方案。 – bschulz

+0

我並不是說用戶名在列表中是唯一的;我的意思是我期望每個用戶名只對應一個用戶(所以你不必擔心'dict'中的衝突條目)。安東尼孔張貼我正在得到的;我發佈的鏈接僅在用戶名的順序很重要時纔有用,但我認爲它可能不會。 –

+0

啊 - 搞錯了。是的 - 你是對的。關於排序順序,我將字典轉換回列表,然後使用帶lambda函數的sort()方法...比我手動重複檢測更快,更簡單,更優雅。非常感謝您指點我正確的道路! – bschulz

0

讓我們說,這是你得到了什麼,

JSON = [ 
     { 

      "name": "fred", 
... 
}, 
     { 

      "name": "peter", 
... 
}, 
     { 

      "name": "fred", 
... 
}, 

轉換字典的這份名單的字典字典中會刪除重複的,就像這樣:

r = dict([(user['name'], user) for user in JSON]) 

r你只能找到弗雷德和彼得的每一個記錄。

+0

作爲一個字典理解,理解會少很多:'{user ['name']:JSON用戶的用戶}' –

+0

不錯!作品!謝謝! – bschulz

+1

只是爲了關閉這個循環......這裏是我的最終代碼'result = dict([(user.name,user)for user in result]) result = [key的值,result.iteritems() ] result.sort(key = lambda d:d.name)' – bschulz