看板 Python 關於我們 聯絡資訊
各位好 想再次詢問關於字典切字的問題,想要詢問「如何有效率的在一份字典中切出指定的所有值」,例如下方的格式中,想要指定share_link,切出裡面的值 j={u'items': [{u'annotations': [],u'share_link': u'a'}, {u'annotations': [],u'share_link': u'b'}, {u'annotations': [],u'share_link': u'c'}, ]} 我最一開始的嘗試方法為用呼叫的方式,例如print "Value: %s" % j.get('items')[0]['share_link'] 確實是可以叫出裡面的所有值,但是效率非常得差,假若’share_link’出現20次,我就要把括號 [0] 裡面的值從0寫到19,共重複20次,想請問有什麼好的解決方法,提升效率。 例如,如下面的虛擬碼,改成指定share_link,只要是share_link就把裡面的值抓出來 虛擬碼: b = j.findall(‘share_link’) print every share_link value -- Sent from my Windows -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.120.251.134 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1479546826.A.1E8.html ※ 編輯: busystudent (59.120.251.134), 11/19/2016 17:55:20
uranusjr: 用迴圈啊 11/19 18:26
koshi0413: For 11/19 18:42
mantour: 你要先說你的j是怎麼來的 j裡面除了items還會有其他 11/20 13:12
mantour: key-value pairs嗎? 11/20 13:13
mantour: items的value一定是list嗎 list裡面的元素都是dict嗎 11/20 13:14
mantour: 每個dict裡面都只有annotation和shared_link兩個key嗎 11/20 13:15
mantour: 還是會有其他組合? 然後你的j為什麼要長這樣 11/20 13:15
mantour: 以上都搞清楚才會知道要怎麼寫才符合你的需求 11/20 13:16
mantour: item裡面的dict如果沒有share_link這個key就跳過嗎 11/20 13:19
s860134: [i.get('share_link') for i in j.get('items')\ 11/20 13:23
s860134: if 'share_link' in i] 11/20 13:24