empz
empz

Reputation: 11788

Python: function to fetch data always returns None

I have this list of dictionaries:

cust = [
        {"id": 1, "name": u"name 1", "bill_amount": 1000},
        {"id": 2, "name": u"name 2", "bill_amount": 5000},
        {"id": 3, "name": u"name 3", "bill_amount": 7600},
        {"id": 4, "name": u"name 4", "bill_amount": 30}
       ]

And I want to get a list of just the names.

Trying this:

def getName(x): x["name"]
print map(getName, cust)

Returns this:

[None, None, None, None]

Why? Am I missing something obvious?

Upvotes: 0

Views: 330

Answers (3)

wim
wim

Reputation: 363043

As already pointed out, your function is not returning anything.

For the record, the pythonic way to do this is not to use map, but to use a list comprehension.

[d['name'] for d in cust]

Upvotes: 3

Andrew Clark
Andrew Clark

Reputation: 208545

You could also use operator.itemgetter() instead of defining your own function for this:

>>> import operator
>>> map(operator.itemgetter("name"), cust)
[u'name 1', u'name 2', u'name 3', u'name 4']

Upvotes: 6

ninjagecko
ninjagecko

Reputation: 91122

def getName(x):
    return x["name"]

In python, a function which returns nothing returns None. Do not confuse this with lambda-syntax (useful but not "pythonic"), which would have been: getName = lambda x: x["name"]

Upvotes: 3

Related Questions