簡體   English   中英

如何在列表中從Python對象提取單個屬性?

[英]How to extract single property from Python object when it is in a list?

我有一個名為Profile的Python對象,它具有first namelast name 我有一個名為Profiles的數組,它是Profile對象的集合:

Profiles = []
Profile  = {}
Profile['firstname'] = "foo"
Profile['lastname'] = "bar"
Profiles.append(Profile)

我需要將此數組作為json發布到Web服務,但是我只想發布firstname屬性。

我發布這樣的數組:

response = urllib2.urlopen(req, json.dumps(Profiles))

如何修改我的代碼以僅張貼名字? 我意識到我可以遍歷並創建一個新列表,但是想知道是否有更簡單的方法?

遍歷列表,並使用列表理解從dict提取所需的元素。

response = urllib2.urlopen(req, json.dumps([p["firstname"] for p in Profiles]))

干得好:

json.dumps([p['firstname'] for p in Profiles])

對於兩個字段,您可以編寫:

json.dumps([{'firstname':p['firstname'],'lastname':p['lastname']} for p in Profiles])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM