Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - NameError: name itemgetter not defined

I just started learning Python came across this very simple code could not get it right:

import operator;

b=[(5,3),(1,3),(1,2),(2,-1),(4,9)]
sorted(b,key=itemgetter(1))

I got the error:

NameError: name 'itemgetter' is not defined.

Any idea?

like image 893
Ricky Nelson Avatar asked Apr 18 '16 04:04

Ricky Nelson


People also ask

What is Itemgetter in Python?

itemgetter(*items) Return a callable object that fetches item from its operand using the operand's __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example: After f = itemgetter(2) , the call f(r) returns r[2] .

How do I use key Itemgetter in Python?

itemgetter() can be used to sort the list based on the value of the given key. Note that an error is raised if a dictionary without the specified key is included. You can do the same with a lambda expression. If the dictionary does not have the specified key, you can replace it with any value with the get() method.

How does operator Itemgetter work?

In two words operator. itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it. So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.


2 Answers

you must import the module like,

import operator

b=[(5,3),(1,3),(1,2),(2,-1),(4,9)]
sorted(b,key=operator.itemgetter(1))
like image 54
Suresh2692 Avatar answered Sep 23 '22 08:09

Suresh2692


to write itemgetter instead of operator.itemgetter can do

from operator import itemgetter
like image 30
iamnotsam Avatar answered Sep 20 '22 08:09

iamnotsam