Skip to content
Advertisement

How to sort objects by multiple keys?

Or, practically, how can I sort a list of dictionaries by multiple keys? I have a list of dicts: and I need to use a multi key sort reversed by Total_Points, then not reversed by TOT_PTS_Misc. This can be done at the command prompt like so: But I have to run this through a function, where I pass in the

Import python package from local directory into interpreter

I’m developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in sys.path.insert(0,’.’). Is there a better way? Also, fails with this error: Answer You can use relative imports only from in a module that was in turn imported as part of

How do I capture SIGINT in Python?

I’m working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a Ctrl+C signal, and I’d like to do some cleanup. In Perl I’d do this: How do I do the analogue of this in Python? Answer Register your handler with signal.signal like this: Code adapted from

Parse annotations from a pdf

I want a python function that takes a pdf and returns a list of the text of the note annotations in the document. I have looked at python-poppler (https://code.launchpad.net/~poppler-python/poppler-python/trunk) but I can not figure out how to get it to give me anything useful. I found the get_annot_mapping method and modified the demo program provided to call it via self.current_page.get_annot_mapping(),

What’s the difference between “2*2” and “2**2” in Python?

What is the difference between the following statements? Statement 1: Statement 2: I see no difference. This raises the following question. Why is Statement 1 used if we can use Statement 2? Answer Try: and to see the difference. ** is the operator for “power of”. In your particular operation, 2 to the power of 2 yields the same as

Get the index of an element in a queryset

I have a QuerySet, let’s call it qs, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let’s call it obj. Now I’d like to know at what index obj has in qs, as efficiently as possible. I know that I could use .index() from Python or possibly loop through qs comparing

Advertisement