Evonet
Evonet

Reputation: 3640

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

I have a Python object called Profile which has first name and last name. I have an array called Profiles which is a collection of Profile objects:

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

I need to post this array as json to a web service, however I only want to post the firstname property.

I'm posting the array like this:

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

How can I modify my code to only post the first names? I realise I can loop through and create a new list, but was wondering if there was an easier way?

Upvotes: 1

Views: 2021

Answers (2)

Bidhan Bhattarai
Bidhan Bhattarai

Reputation: 1060

Here you go:

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

And for two fields, you can just write:

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

Upvotes: 1

ZdaR
ZdaR

Reputation: 22954

Iterate over the list and extract the desired elements from the dict using list comprehension.

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

Upvotes: 4

Related Questions