title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
What scalability issues are associated with NetworkX? | 7,978,840 | 22 | 2011-11-02T10:27:32Z | 7,979,956 | 13 | 2011-11-02T12:01:53Z | [
"python",
"graph",
"social-networking",
"libraries"
] | I'm interested in network analysis on large networks with millions of nodes and tens of millions of edges. I want to be able to do things like parse networks from many formats, find connected components, detect communities, and run centrality measures like PageRank.
I am attracted to NetworkX because it has a nice api... | Your big issue will be memory. Python simply *cannot* handle tens of millions of objects, without jumping through hoops in your class implementation. The memory overhead of many objects is too high, you hit 2GB, and 32 bit code won't work. There's ways around it - using slots, arrays, or numpy. It *should* be OK, becau... |
How to render my TextArea with WTForms? | 7,979,548 | 10 | 2011-11-02T11:25:19Z | 23,256,596 | 26 | 2014-04-23T22:46:35Z | [
"python",
"wtforms"
] | To render my textareafield with a specified number of columns and rows with WTForms, how do I set the number of columns and rows? I followed the instructions from this question but it didn't work:
[How to specify rows and columns of a <textarea > tag using wtforms](http://stackoverflow.com/questions/4930747/how-to-spe... | Very old question, but since the WTF-Form documentation isn't clear I'm posting my working example. OP, hope you are not still working on this. :-)
**form**
```
from flask_wtf import Form
from wtforms.fields import StringField
from wtforms.widgets import TextArea
class PostForm(Form):
title = StringField(u'title... |
In Git, how do I configure a hook to run a server-side commands after a commit is accepted? | 7,980,053 | 5 | 2011-11-02T12:10:57Z | 7,980,527 | 10 | 2011-11-02T12:46:02Z | [
"python",
"django",
"git",
"localization",
"githooks"
] | I'm trying to figure out my way with the Django localistion stuff and from what i've understood, the `makemessages` command needs to be run every time you change some strings in code. I was thinking of simplifying this process by using a server-side Git hook.
I have no knowledge about Git hooks and couldn't find any r... | Sure thing!
Add a script called `post-receive` to the server side git repository in the `.git/hooks/` directory.
Make sure that the file is executable.
Call makemessages from the script.
Done! (I think...)
You'll find some example scripts in the directory already, with most available hooks.
Have a look at [the pr... |
Splitting large text file by a delimiter in Python | 7,980,288 | 3 | 2011-11-02T12:27:27Z | 7,980,348 | 9 | 2011-11-02T12:32:15Z | [
"python",
"text-parsing"
] | I imaging this is going to be a simple task but I can't find what I am looking for exactly in previous StackOverflow questions to here goes...
I have large text files in a proprietry format that look comething like this:
```
:Entry
- Name
John Doe
- Date
20/12/1979
:Entry
-Name
Jane Doe
- Date
21/12/1979
```
And s... | You could use [itertools.groupby](http://docs.python.org/library/itertools.html#itertools.groupby) to group lines that occur after `:Entry` into lists:
```
import itertools as it
filename='test.dat'
with open(filename,'r') as f:
for key,group in it.groupby(f,lambda line: line.startswith(':Entry')):
if not... |
how to remove an element in lxml | 7,981,840 | 35 | 2011-11-02T14:19:00Z | 7,981,894 | 66 | 2011-11-02T14:22:54Z | [
"python",
"xml",
"lxml"
] | I need to completely remove elements, based on the contents of an attribute, using python's lxml. Example:
```
import lxml.etree as et
xml="""
<groceries>
<fruit state="rotten">apple</fruit>
<fruit state="fresh">pear</fruit>
<fruit state="fresh">starfruit</fruit>
<fruit state="rotten">mango</fruit>
<fruit s... | Use the [`remove`](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.remove) method of an xmlElement :
```
tree=et.fromstring(xml)
for bad in tree.xpath("//fruit[@state=\'rotten\']"):
bad.getparent().remove(bad) # here I grab the parent of the element to call the remove dir... |
how to remove an element in lxml | 7,981,840 | 35 | 2011-11-02T14:19:00Z | 7,981,897 | 15 | 2011-11-02T14:22:55Z | [
"python",
"xml",
"lxml"
] | I need to completely remove elements, based on the contents of an attribute, using python's lxml. Example:
```
import lxml.etree as et
xml="""
<groceries>
<fruit state="rotten">apple</fruit>
<fruit state="fresh">pear</fruit>
<fruit state="fresh">starfruit</fruit>
<fruit state="rotten">mango</fruit>
<fruit s... | You're looking for the `remove` function. Call the tree's remove method and pass it a subelement to remove.
```
import lxml.etree as et
xml="""
<groceries>
<fruit state="rotten">apple</fruit>
<fruit state="fresh">pear</fruit>
<punnet>
<fruit state="rotten">strawberry</fruit>
<fruit state="fresh">blueber... |
Unix socket credential passing in Python | 7,982,714 | 8 | 2011-11-02T15:14:39Z | 7,982,749 | 16 | 2011-11-02T15:16:10Z | [
"python",
"linux",
"sockets",
"credentials"
] | How is Unix socket credential passing accomplished in Python? | Internet searches on this topic came up with surprisingly few results. I figured I'd post the question and answer here for others interested in this topic.
The following client and server applications demonstrate how to accomplish this on Linux with the standard python interpreter. No extensions are required but, due ... |
Subclassing builtin types in Python 2 and Python 3 | 7,983,243 | 21 | 2011-11-02T15:48:00Z | 7,984,017 | 10 | 2011-11-02T16:42:00Z | [
"python",
"python-3.x",
"subclass",
"built-in-types"
] | When subclassing builtin types, I noticed a rather important difference between Python 2 and Python 3 in the return type of the methods of the built-in types. The following code illustrates this for sets:
```
class MySet(set):
pass
s1 = MySet([1, 2, 3, 4, 5])
s2 = MySet([1, 2, 3, 6, 7])
print(type(s1.union(s2)... | This isn't a general change for built-in types when moving from Python 2.x to 3.x -- `list` and `int`, for example, have the same behaviour in 2.x and 3.x. Only the set type was changed to bring it in line with the other types, as discussed in [this bug tracker issue](http://bugs.python.org/issue1721812).
I'm afraid t... |
How to switch byte order of binary data | 7,983,684 | 7 | 2011-11-02T16:17:25Z | 7,983,775 | 8 | 2011-11-02T16:23:33Z | [
"python",
"struct",
"pack"
] | I have a binary file which I'm reading where some 2 byte values are stored in 'reverse' byte order (little endian?), eg.
```
1D 00 13 00 27 00 3B 00 45 00 31 00 4F
```
The original program that created these values stores them internally as shorts. Those values should correspond to: 29, 19, 39, 59, 69, 49, 79. I'm ... | Byte order is specified with a single character, at the beginning of the format string.
```
values = struct.unpack('!7h', data)
``` |
How to test Python function decorators? | 7,983,709 | 6 | 2011-11-02T16:19:44Z | 7,983,839 | 7 | 2011-11-02T16:28:38Z | [
"python",
"unit-testing",
"decorator"
] | I'm trying to write unit tests to ensure correctness of various decorators I've written. Here's the start of the code I'm trying to write:
```
import unittest
from memoizer import Memoizer
from strategies.mru import MRU
@Memoizer(strategy=MRU(maxsize=10))
def fib(x):
if x < 2:
return 1
else:
return fib(... | Take a look at the tests in the standard library for examples: <http://hg.python.org/cpython/file/3.2/Lib/test/test_functools.py#l553>
I usually add some instrumentation to the function being wrapped so that I can monitor the calls.
Instead of memoizing the test function at the module level, I create the memoized fun... |
Using Django ORM get_or_create with multiple databases | 7,983,711 | 5 | 2011-11-02T16:19:50Z | 7,983,870 | 10 | 2011-11-02T16:31:06Z | [
"python",
"django",
"django-orm"
] | Django's ORM supports querying from a specific database (when multiple are defined in your project) via the .using() function for filter-based operations.
e.g. `MyModel.objects.filter(name='Bob').using('my_non_default_database')`
How would you do the equivalent when creating new records, via the class MyModel() or sh... | `using` is a method on the `MyModel.objects` manager, so you can do
```
MyModel.objects.using('my_non_default_database').get_or_create(name="Bob")
```
If you have a MyModel instance, you can use the using keyword to specify the database to save to. The [django docs](https://docs.djangoproject.com/en/dev/topics/db/mul... |
Python: handle broken unicode bytes when parsing JSON string | 7,984,146 | 11 | 2011-11-02T16:49:09Z | 7,984,562 | 10 | 2011-11-02T17:18:33Z | [
"python",
"json",
"unicode"
] | My code makes gets some content from an UserVoice site. As you might know, UserVoice is a shitty piece of software that can't handle data correctly; indeed, to reduce the amount of text on the search page, they cut the text at, let's say, 300 characters and then add a "..." to the end. Thing is, **they don't care cutti... | You don't ask simplejson to ignore them. When I got similar problem like yours I just ran `.decode('utf-8', 'ignore').encode('utf-8')` and proceed. |
Using strip on lists | 7,984,169 | 38 | 2011-11-02T16:50:45Z | 7,984,192 | 77 | 2011-11-02T16:52:38Z | [
"python",
"list",
"strip"
] | I have to take a large list of words in the form:
```
['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
```
and then using the strip function, turn it into:
```
['this', 'is', 'a', 'list', 'of', 'words']
```
I thought that what I had written would work, but I keep getting an error saying:
> "'list' object has... | ```
>>> my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> map(str.strip, my_list)
['this', 'is', 'a', 'list', 'of', 'words']
``` |
Using strip on lists | 7,984,169 | 38 | 2011-11-02T16:50:45Z | 7,984,202 | 59 | 2011-11-02T16:53:03Z | [
"python",
"list",
"strip"
] | I have to take a large list of words in the form:
```
['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
```
and then using the strip function, turn it into:
```
['this', 'is', 'a', 'list', 'of', 'words']
```
I thought that what I had written would work, but I keep getting an error saying:
> "'list' object has... | list comprehension?
`[x.strip() for x in lst]` |
Using strip on lists | 7,984,169 | 38 | 2011-11-02T16:50:45Z | 7,984,212 | 23 | 2011-11-02T16:53:16Z | [
"python",
"list",
"strip"
] | I have to take a large list of words in the form:
```
['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
```
and then using the strip function, turn it into:
```
['this', 'is', 'a', 'list', 'of', 'words']
```
I thought that what I had written would work, but I keep getting an error saying:
> "'list' object has... | You can use [lists comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions):
```
strip_list = [item.strip() for item in lines]
```
Or the [`map`](http://docs.python.org/library/functions.html#map) function:
```
# with a lambda
strip_list = map(lambda it: it.strip(), lines)
# without ... |
ValueError: invalid literal for float() in Python | 7,986,459 | 5 | 2011-11-02T19:48:10Z | 7,987,522 | 7 | 2011-11-02T21:26:25Z | [
"python",
"floating-point",
"literals",
"iterable"
] | To all:
I have curious if someone can help me understand the error: ValueError: invalid literal for float(). I am getting this when I am passing a text file to a list then trying to convert this list to float values.
```
a = open("input.txt","r")
lines = a.readlines()
b = map(float, lines)
```
What is odd, at least ... | You don't need readlines in this case -- it's a waste of time and memory.
If you want a list of lists of floats:
```
b = [[float(v) for v in line.rstrip('\n').split('\t')] for line in a]
```
or just one big list of floats:
```
b = [float(v) for line in a for v in line.rstrip('\n').split('\t')]
``` |
Matplotlib: how to set the current figure? | 7,986,567 | 43 | 2011-11-02T19:57:17Z | 7,986,664 | 11 | 2011-11-02T20:06:23Z | [
"python",
"matplotlib"
] | This is hopefully a simple question but I can't figure it out at the moment. I want to use matplotlib to show 2 figures and then use them interactively. I create the figures with:
```
import matplotlib
import pylab as pl
f1 = pl.figure()
f2 = pl.figure()
```
and can use the MATLAB-like pyplot interface to plot and d... | Give each figure a number:
```
f1 = pl.figure(1)
f2 = pl.figure(2)
# use f2
pl.figure(1) # make f1 active again
``` |
Matplotlib: how to set the current figure? | 7,986,567 | 43 | 2011-11-02T19:57:17Z | 7,987,462 | 41 | 2011-11-02T21:19:54Z | [
"python",
"matplotlib"
] | This is hopefully a simple question but I can't figure it out at the moment. I want to use matplotlib to show 2 figures and then use them interactively. I create the figures with:
```
import matplotlib
import pylab as pl
f1 = pl.figure()
f2 = pl.figure()
```
and can use the MATLAB-like pyplot interface to plot and d... | You can simply set figure `f1` as the new current figure with:
```
pl.figure(f1.number)
```
Another option is to give names (or numbers) to figures, which might help make the code easier to read:
```
pl.figure("Share values")
# ... some plots ...
pl.figure("Profits")
# ... some plots ...
pl.figure("Share values") ... |
How do you convert a naive datetime to DST-aware datetime in Python? | 7,986,776 | 10 | 2011-11-02T20:15:23Z | 7,986,847 | 12 | 2011-11-02T20:21:25Z | [
"python",
"datetime",
"timezone",
"pytz"
] | I'm currently working on the backend for a calendaring system that returns naive Python datetimes. The way the front end works is the user creates various calendar events, and the frontend returns the naive version of the event they created (for example, if the user selects October 5, 2020 from 3:00pm-4:00pm, the front... | Pytz's `localize` function can do this: <http://pytz.sourceforge.net/#localized-times-and-date-arithmetic>
```
from datetime import datetime
import pytz
tz = pytz.timezone('US/Pacific')
naive_dt = datetime(2020, 10, 5, 15, 0, 0)
utc_dt = tz.localize(naive_dt, is_dst=None).astimezone(pytz.utc)
# -> 2020-10-05 22:... |
Getting the subsets of a set in Python | 7,988,695 | 5 | 2011-11-02T23:39:47Z | 7,988,747 | 11 | 2011-11-02T23:47:10Z | [
"python",
"algorithm",
"math",
"combinatorics"
] | Suppose we need to write a function that gives the list of all the subsets of a set. The function and the doctest is given below. And we need to complete the whole definition of the function
```
def subsets(s):
"""Return a list of the subsets of s.
>>> subsets({True, False})
[{False, True}, {False}, {True}, ... | Look at the [powerset()](http://en.wikipedia.org/wiki/Power_set) recipe in the [itertools docs](http://docs.python.org/library/itertools.html#recipes).
```
from itertools import chain, combinations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
... |
what does this django regex mean? `?P` | 7,988,942 | 29 | 2011-11-03T00:20:20Z | 7,988,955 | 11 | 2011-11-03T00:22:47Z | [
"python",
"regex",
"django",
"capturing-group"
] | I have the following regex in my urls.py and I'd like to know what it means. Specifically the `(?P<category_slug>` portion of the regex.
`r'^category/(?P<category_slug>[-\w]+)/$` | `(?P<category_slug>)` creates a match group named `category_slug`.
The regex itself matches a string starting with `category/` and then a mix of alphanumeric characters, the dash `-` and the underscore `_`, followed by a trailing slash.
Example URLs accepted by the regex:
* category/foo/
* category/foo\_bar-baz/
* c... |
what does this django regex mean? `?P` | 7,988,942 | 29 | 2011-11-03T00:20:20Z | 7,988,963 | 21 | 2011-11-03T00:24:44Z | [
"python",
"regex",
"django",
"capturing-group"
] | I have the following regex in my urls.py and I'd like to know what it means. Specifically the `(?P<category_slug>` portion of the regex.
`r'^category/(?P<category_slug>[-\w]+)/$` | `(?P<name>regex)` - Round brackets group the regex between them. They capture the text matched by the regex inside them that can be referenced by the name between the sharp brackets. The name may consist of letters and digits.
Copy paste from: <http://www.regular-expressions.info/refext.html> |
what does this django regex mean? `?P` | 7,988,942 | 29 | 2011-11-03T00:20:20Z | 7,989,007 | 32 | 2011-11-03T00:32:22Z | [
"python",
"regex",
"django",
"capturing-group"
] | I have the following regex in my urls.py and I'd like to know what it means. Specifically the `(?P<category_slug>` portion of the regex.
`r'^category/(?P<category_slug>[-\w]+)/$` | In django, named capturing groups are passed to your view as keyword arguments.
Unnamed capturing groups (just a parenthesis) are passed to your view as arguments.
The ?P is a named capturing group, as opposed to an unnamed capturing group.
<http://docs.python.org/library/re.html>
> `(?P<name>...)` Similar to regul... |
Preventing a class from direct instantiation in Python | 7,989,042 | 9 | 2011-11-03T00:37:40Z | 7,989,071 | 8 | 2011-11-03T00:41:41Z | [
"python",
"class",
"locking",
"superclass"
] | I have a super class with a method that calls other methods that are only defined in its sub classes. That's why, when I create an instance of my super class and call its method, it cannot find the method and raises an error.
Here is an example:
```
class SuperClass(object):
def method_one(self):
value = self.... | You're talking about Abstract Base Classes, and the Python language does not support them natively.
However, in the standard library, there is a module you can use to help you along. Check out the [abc](http://docs.python.org/library/abc.html) documentation. |
Preventing a class from direct instantiation in Python | 7,989,042 | 9 | 2011-11-03T00:37:40Z | 7,989,101 | 14 | 2011-11-03T00:46:37Z | [
"python",
"class",
"locking",
"superclass"
] | I have a super class with a method that calls other methods that are only defined in its sub classes. That's why, when I create an instance of my super class and call its method, it cannot find the method and raises an error.
Here is an example:
```
class SuperClass(object):
def method_one(self):
value = self.... | Your approach is a typical [framework pattern](http://en.wikipedia.org/wiki/Software_framework).
Using \_\_init\_\_ to verify that `type(self) is not SuperClass` is a reasonable way to make sure the SuperClass hasn't been instantiated directly.
The other common approach is to provide stub methods that `raise NotImple... |
Preventing a class from direct instantiation in Python | 7,989,042 | 9 | 2011-11-03T00:37:40Z | 7,990,308 | 14 | 2011-11-03T04:35:33Z | [
"python",
"class",
"locking",
"superclass"
] | I have a super class with a method that calls other methods that are only defined in its sub classes. That's why, when I create an instance of my super class and call its method, it cannot find the method and raises an error.
Here is an example:
```
class SuperClass(object):
def method_one(self):
value = self.... | I would override `__new__()` in the base class and simply fail to instantiate at all if it's the base class.
```
class BaseClass(object):
def __new__(cls, *args, **kwargs):
if cls is BaseClass:
raise TypeError("base class may not be instantiated")
return object.__new__(cls, *args, **kw... |
Use libraries installed by R for other programs? | 7,989,048 | 3 | 2011-11-03T00:38:56Z | 7,989,636 | 9 | 2011-11-03T02:27:27Z | [
"python",
"unix"
] | When R installs a package that contains other programs/libraries (e.g., `hdf5`, `SQLite`), can I use those in other programs? For instance, I have `hdf5.so` installed in `/Library/Frameworks/R.framework/Versions/2.13/Resources/library/hdf5/libs/x86_64/` - can I use this instead of installing `hdf5` for use by Python (`... | As a general rules, no. You also may be misreading this: `hdf5.so` is the *binding* from R to the hdf5 libraries. E.g. when (on a Linux box) I ask the linker what a given R library links to, I get something like
```
edd@max:~$ ldd /usr/lib/R/site-library/XML/libs/XML.so
linux-vdso.so.1 => (0x00007fffcbf75000... |
Finding unique points in numpy array | 7,989,722 | 8 | 2011-11-03T02:44:41Z | 7,989,878 | 7 | 2011-11-03T03:14:26Z | [
"python",
"numpy"
] | What is a faster way of finding unique x,y points (removing duplicates) in a numpy array like:
```
points = numpy.random.randint(0, 5, (10,2))
```
I thought of converting points to a complex numbers and then checking for unique, but that seems rather convoluted:
```
b = numpy.unique(points[:,0] + 1j * points[:,1])
p... | I think you have a very good idea here. Think about the underlying block of memory used to represent the data in `points`. We tell numpy to regard that block as representing an array of shape (10,2) with dtype `int32` (32-bit integers), but it is almost costless to tell numpy to regard that same block of memory as repr... |
Opening a process with Popen and getting the PID | 7,989,922 | 7 | 2011-11-03T03:22:19Z | 7,989,942 | 10 | 2011-11-03T03:26:26Z | [
"python",
"subprocess",
"popen"
] | I'm working on a nifty little function:
```
def startProcess(name, path):
"""
Starts a process in the background and writes a PID file
returns integer: pid
"""
# Check if the process is already running
status, pid = processStatus(name)
if status == RUNNING:
raise AlreadyStartedEr... | From the documentation at <http://docs.python.org/library/subprocess.html>:
> Popen.pid The process ID of the child process.
>
> Note that if you set the shell argument to True, this is the process
> ID of the spawned shell.
If `shell` is false, it should behave as you expect, I think. |
Pythonic way to append list of strings to an array | 7,990,235 | 4 | 2011-11-03T04:23:05Z | 7,990,252 | 8 | 2011-11-03T04:25:34Z | [
"python"
] | I'm new to Python and come from a Java background. I'd like to know the most Pythonic way of writing this code:
```
entry_list = []
for entry in feed.entry:
entry_list.append(entry.title.text)
```
Basically for each element in the feed, I'd like to append that element's title to a list.
I don't know if I should ... | most pythonic code I can think of:
```
entry_list = [entry.title.text for entry in feed.entry]
```
This is a [list comprehension](http://docs.python.org/tutorial/datastructures.html) which will construct a new list out of the elements in feed.entry.title.text.
To append you will need to do:
```
entry_list.extend([e... |
Easy visualization and analysis of social network with Python? | 7,991,138 | 19 | 2011-11-03T06:44:56Z | 15,455,966 | 17 | 2013-03-16T23:32:04Z | [
"python",
"social-networking",
"social-graph"
] | For a school project I need to define a [social network](http://en.wikipedia.org/wiki/Social_network), analyze it and draw it. I could both draw it by hand and analyze it (calculate various metrics) by hand. But being a Python lover, I hope that there is a Python tool for this.
I am dreaming of the social graph equiva... | *[networkx](http://networkx.github.com/)* is a very powerful and flexible Python library for working with network graphs. Directed and undirected connections can be used to connect nodes. Networks can be constructed by adding nodes and then the edges that connect them, or simply by listing edge pairs (undefined nodes w... |
How to get variable length placeholders in a Python call to SQLite3 | 7,991,183 | 11 | 2011-11-03T06:51:03Z | 7,991,230 | 12 | 2011-11-03T06:57:59Z | [
"python",
"sqlite3"
] | Is there a way to use variable length placeholders in an SQL query?
Right now with a 3-tuple, I write something like this:
```
c.execute('SELECT * FROM table WHERE word IN (?, ?, ?)', tup)
```
But what if the *tup* can be of differing lengths, perhaps a 4-tuple or 2-tuple? Is there a syntax for using placeholders in... | You'd have to do something like this (to use your example):
```
tup = ... # some sequence/tuple of unknown length
sql = 'SELECT * FROM table WHERE word IN (%s)' % ', '.join('?' for a in tup)
c.execute(sql, tup)
```
This way you're dynamically creating the placeholder list and formatting the SQL string before the sqli... |
Identifying Excel Sheet cell color code using XLRD package | 7,991,209 | 23 | 2011-11-03T06:56:17Z | 7,991,458 | 29 | 2011-11-03T07:29:06Z | [
"python",
"excel",
"xlrd"
] | I am writing a python script to read data from an excel sheet using [xlrd](http://pypi.python.org/pypi/xlrd). Few of the cells of the the work sheet are highlighted with different color and I want to identify the color code of the cell. Is there any way to do that ? An example would be really appreciated. | Here is one way to handle this:
```
import xlrd
book = xlrd.open_workbook("sample.xls", formatting_info=True)
sheets = book.sheet_names()
print "sheets are:", sheets
for index, sh in enumerate(sheets):
sheet = book.sheet_by_index(index)
print "Sheet:", sheet.name
rows, cols = sheet.nrows, sheet.ncols
p... |
Python tuple trailing comma syntax rule | 7,992,559 | 53 | 2011-11-03T09:23:46Z | 7,992,642 | 29 | 2011-11-03T09:30:25Z | [
"python",
"syntax",
"tuples"
] | In the case of a single element tuple, the trailing comma is required.
```
a = ('foo',)
```
What about a tuple with multiple elements? It seems that whether the trailing comma exists or not, they are both valid. Is this correct? Having a trailing comma is easier for editing in my opinion. Is that a bad coding style?
... | It is only required for single-item tuples to disambiguate defining a tuple or an expression surrounded by parentheses.
For more than one item, it is no longer necessary since it is perfectly clear it is a tuple. However, the trailing comma is allowed to make defining them using multiple lines easier. You could add to... |
Python tuple trailing comma syntax rule | 7,992,559 | 53 | 2011-11-03T09:23:46Z | 7,992,643 | 37 | 2011-11-03T09:30:27Z | [
"python",
"syntax",
"tuples"
] | In the case of a single element tuple, the trailing comma is required.
```
a = ('foo',)
```
What about a tuple with multiple elements? It seems that whether the trailing comma exists or not, they are both valid. Is this correct? Having a trailing comma is easier for editing in my opinion. Is that a bad coding style?
... | In all cases except the empty tuple the comma is the important thing. Parentheses are only required when required for other syntactic reasons: to distinguish a tuple from a set of function arguments, operator precedence, or to allow line breaks.
The trailing comma for tuples, lists, or function arguments is good style... |
Python tuple trailing comma syntax rule | 7,992,559 | 53 | 2011-11-03T09:23:46Z | 7,992,649 | 7 | 2011-11-03T09:31:13Z | [
"python",
"syntax",
"tuples"
] | In the case of a single element tuple, the trailing comma is required.
```
a = ('foo',)
```
What about a tuple with multiple elements? It seems that whether the trailing comma exists or not, they are both valid. Is this correct? Having a trailing comma is easier for editing in my opinion. Is that a bad coding style?
... | It's optional: see the [Python wiki](http://wiki.python.org/moin/TupleSyntax).
Summary: single-element tuples *need a trailing comma*, but it's *optional* for multiple-element tuples. |
Python tuple trailing comma syntax rule | 7,992,559 | 53 | 2011-11-03T09:23:46Z | 17,002,144 | 20 | 2013-06-08T17:42:20Z | [
"python",
"syntax",
"tuples"
] | In the case of a single element tuple, the trailing comma is required.
```
a = ('foo',)
```
What about a tuple with multiple elements? It seems that whether the trailing comma exists or not, they are both valid. Is this correct? Having a trailing comma is easier for editing in my opinion. Is that a bad coding style?
... | Another advantage of trailing commas is that it makes diffs look nicer. If you started with
```
a = [
1,
2,
3
]
```
and changed it to
```
a = [
1,
2,
3,
4
]
```
The diff would look like
```
a = [
1,
2,
- 3
+ 3,
+ 4
]
```
Whereas if you had started with a trailing c... |
Cannot access AppStats on deployed version | 7,992,949 | 2 | 2011-11-03T09:55:29Z | 7,993,240 | 7 | 2011-11-03T10:21:30Z | [
"python",
"google-app-engine",
"appstats"
] | I have enabled appstats for my Python App Engine application, and I can access it locally under the /\_ah/stats/ url but when I deploy the application and visit the appspot.com under my application in the UI there is no custom AppStats link as it should have. In my yaml file I define:
```
builtins:
- appstats: on
```
... | There shouldn't be a link in the managment site (unless you add it using [admin\_console](http://code.google.com/appengine/docs/python/config/appconfig.html#Administration_Console_Custom_Pages)).
The stats should be available at your-app-id.appspot.com/\_ah/stats |
Running Scrapy tasks in Python | 7,993,680 | 7 | 2011-11-03T10:55:31Z | 7,994,137 | 10 | 2011-11-03T11:30:03Z | [
"python",
"scrapy"
] | My Scrapy script seems to work just fine when I run it in 'one off' scenarios from the command line, but if I try running the code twice in the same python session I get this error:
"ReactorNotRestartable"
Why?
The offending code (last line throws the error):
```
crawler = CrawlerProcess(settings)
crawler.install()... | Close to Joël's answer, but I want to elaborate a bit more than is possible in the comments. If you look at the [Crawler source code](http://dev.scrapy.org/browser/scrapy/crawler.py), you see that the `CrawlerProcess` class has a `start`, but also a `stop` function. This `stop` function takes care of cleaning up the i... |
Fast in-place replacement of some values in a numpy array | 7,994,133 | 14 | 2011-11-03T11:29:47Z | 7,994,184 | 20 | 2011-11-03T11:33:34Z | [
"python",
"performance",
"numpy"
] | There has got to be a faster way to do in place replacement of values, right? I've got a 2D array representing a grid of elevations/bathymetry. I want to replace anything over 0 with NAN and this way is super slow:
```
for x in range(elevation.shape[0]):
for y in range(elevation.shape[1]):
if elevation[x,y... | The following will do it:
```
elevation[elevation > 0] = numpy.NAN
```
See [Indexing with Boolean Arrays](http://www.scipy.org/Tentative_NumPy_Tutorial#head-d55e594d46b4f347c20efe1b4c65c92779f06268) in the NumPy tutorial. |
Efficient thresholding filter of an array with numpy | 7,994,394 | 37 | 2011-11-03T11:52:45Z | 7,994,426 | 58 | 2011-11-03T11:55:52Z | [
"python",
"filter",
"numpy",
"threshold"
] | I need to filter an array to remove the elements that are lower than a certain threshold. My current code is like this:
```
threshold = 5
a = numpy.array(range(10)) # testing data
b = numpy.array(filter(lambda x: x >= threshold, a))
```
The problem is that this creates a temporary list, using a filter with a lambda f... | `b = a[a>threshold]` this should do
I tested as follows:
```
import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()
t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0
t0 = datetime.datetime.now()
flt = np.arra... |
Choosing a file in Python3 | 7,994,461 | 8 | 2011-11-03T11:58:37Z | 7,994,990 | 21 | 2011-11-03T12:38:02Z | [
"python",
"python-3.x",
"tkinter"
] | Where is the tkFileDialog module in Python 3? The question [choosing a file in python - simple GUI](http://stackoverflow.com/questions/3579568/choosing-a-file-in-python-simple-gui) references the module using:
```
from Tkinter import Tk
from tkFileDialog import askopenfilename
```
but using that (after changing Tkint... | You're looking for `tkinter.filedialog` as noted [in the docs](http://docs.python.org/release/3.1.4/library/tkinter.html#tkinter-modules).
```
from tkinter import filedialog
```
You can look at what methods/classes are in `filedialog` by running `help(filedialog)` in the python interpreter. I think `filedialog.LoadFi... |
Numpy python find minimum value of each column and subtract this value from each column | 7,994,992 | 18 | 2011-11-03T12:38:12Z | 7,995,015 | 28 | 2011-11-03T12:39:51Z | [
"python",
"numpy"
] | Can anyone help with a snippet of code using numpy and python?
Given an numpy array such as
```
a = array([[1,11], [3,9], [5,7]]
```
I want to find the minimun value of each column, so 1 and 7 and then subtract this value from the respective columns,
```
a = array([[0,4], [2,2], [4,0]]
``` | ```
>>> a - a.min(axis=0)
array([[0, 4],
[2, 2],
[4, 0]])
``` |
Iterate through checkboxes in Flask | 7,996,075 | 14 | 2011-11-03T13:56:03Z | 7,997,056 | 27 | 2011-11-03T14:58:29Z | [
"python",
"flask",
"jinja2"
] | I have a Jinja2 template that looks like this:
```
<form action="" method=post>
<table>
<tr>
<th></th>
<th>ID</th>
<th>Title</th>
</tr>
{% for page in pages %}
<tr>
<td><input type=checkbox name=do_delete value="{{ page['id'] }... | Flask's `request` object (well, actually the class that is returned by the `LocalProxy` instance that is `request`) is a subclass of werkzeug's [`MultiDict`](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict) data structure - which includes a [`getlist`](http://werkzeug.pocoo.org/docs/dat... |
What is StringIO in python used for in reality? | 7,996,479 | 48 | 2011-11-03T14:22:45Z | 7,996,541 | 25 | 2011-11-03T14:26:43Z | [
"python",
"string",
"caching",
"io"
] | I am not a pro and I have been scratching my head over understanding what exactly StringIO is used for. I have been looking around the internet for some examples. However, almost all of the examples are very abstract. And they just show "how" to use it. But none of them show "why" and "in which circumstances" one shoul... | StringIO gives you file-like access to strings, so you can use an existing module that deals with a file and change almost nothing and make it work with strings.
For example, say you have a logger that writes things to a file and you want to instead send the log output over the network. You can read the file and write... |
What is StringIO in python used for in reality? | 7,996,479 | 48 | 2011-11-03T14:22:45Z | 7,996,613 | 68 | 2011-11-03T14:30:28Z | [
"python",
"string",
"caching",
"io"
] | I am not a pro and I have been scratching my head over understanding what exactly StringIO is used for. I have been looking around the internet for some examples. However, almost all of the examples are very abstract. And they just show "how" to use it. But none of them show "why" and "in which circumstances" one shoul... | It's used when you have some API that only takes files, but you need to use a string. For example, to compress a string using the [gzip](http://docs.python.org/library/gzip.html) module in Python 2:
```
import gzip
import StringIO
stringio = StringIO.StringIO()
gzip_file = gzip.GzipFile(fileobj=stringio, mode='w')
gz... |
What is StringIO in python used for in reality? | 7,996,479 | 48 | 2011-11-03T14:22:45Z | 7,996,667 | 9 | 2011-11-03T14:33:59Z | [
"python",
"string",
"caching",
"io"
] | I am not a pro and I have been scratching my head over understanding what exactly StringIO is used for. I have been looking around the internet for some examples. However, almost all of the examples are very abstract. And they just show "how" to use it. But none of them show "why" and "in which circumstances" one shoul... | In cases where you want a file-like object that ACTS like a file, but is writing to an in-memory string buffer: StringIO is the tool. If you're building large strings, such as plain-text documents, and doing a lot of string concatenation, you might find it easier to just use StringIO instead of a bunch of `mystr += 'mo... |
What is StringIO in python used for in reality? | 7,996,479 | 48 | 2011-11-03T14:22:45Z | 7,998,400 | 7 | 2011-11-03T16:25:40Z | [
"python",
"string",
"caching",
"io"
] | I am not a pro and I have been scratching my head over understanding what exactly StringIO is used for. I have been looking around the internet for some examples. However, almost all of the examples are very abstract. And they just show "how" to use it. But none of them show "why" and "in which circumstances" one shoul... | Couple of things I personally have used it for:
1. Whole-file caching. I have a script that reads PDFs and does validation of various things about them. The PDF library I'm using takes an open file in its document constructor. I originally just opened the PDF I was interested in reading, however when I changed it to r... |
Python 3D polynomial surface fit, order dependent | 7,997,152 | 9 | 2011-11-03T15:03:47Z | 7,997,925 | 25 | 2011-11-03T15:56:08Z | [
"python",
"scipy",
"geometry-surface"
] | I am currently working with astronomical data among which I have comet images. I would like to remove the background sky gradient in these images due to the time of capture (twilight). The first program I developed to do so took user selected points from Matplotlib's "ginput" (x,y) pulled the data for each coordinate (... | Griddata uses a spline fitting. A 3rd order spline is not the same thing as a 3rd order polynomial (instead, it's a different 3rd order polynomial at every point).
If you just want to fit a 2D, 3rd order polynomial to your data, then do something like the following to estimate the 16 coefficients using *all* of your d... |
Check if an item equals to one out of many elements in Python | 7,997,749 | 4 | 2011-11-03T15:44:12Z | 7,997,789 | 8 | 2011-11-03T15:47:16Z | [
"python"
] | I want to check if an item from a list equals to any one element out of a given set of n elements, if yes, do some thing.
For example, the most intuitive but of course cumbersome and ugly way is:
```
for item in List:
if (item == element1) or (item == element2) or ... or (item == elementn):
do something
`... | You use the `in` operator:
```
elements = set((element1, element2, ..., elementn))
...
if item in elements:
do something
```
Use either a set or a tuple for the elements: a set is faster for lookups but requires the elements be hashable. A tuple is lighter weight for a few elements but gets slower if there are mor... |
Do PyImport_ImportModule and import statement load into different namespace? | 7,998,816 | 5 | 2011-11-03T16:57:29Z | 7,999,384 | 8 | 2011-11-03T17:37:14Z | [
"c++",
"python",
"import",
"python-c-api",
"python-embedding"
] | Here is canonical example of a program [extending embedded Python 3.x](http://docs.python.org/release/3.2.1/extending/embedding.html) in C/C++:
```
#include <Python.h>
//// Definition of 'emb' Python module ////////////////////
static PyObject* emb_foo(PyObject *self, PyObject *args)
{
char const* n = "I am foo";
... | `__import__` doesn't put the module in any namespace at all, but returns it instead.
`import` calls `__import__`, plus it stores the result in a variable.
The [docs](http://docs.python.org/release/3.2.1/library/functions.html#__import__) say that `import spam` does something similar to:
```
spam = __import__('spam', g... |
Python datetime to string without microsecond component | 7,999,935 | 112 | 2011-11-03T18:18:11Z | 7,999,959 | 78 | 2011-11-03T18:19:44Z | [
"python",
"datetime",
"datetime-format"
] | I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is `2011-11-03 11:07:04` (followed by `+00:00`, but that's not germane).
What's the best way to create such a string (*without*... | ```
>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07
``` |
Python datetime to string without microsecond component | 7,999,935 | 112 | 2011-11-03T18:18:11Z | 7,999,977 | 253 | 2011-11-03T18:22:00Z | [
"python",
"datetime",
"datetime-format"
] | I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is `2011-11-03 11:07:04` (followed by `+00:00`, but that's not germane).
What's the best way to create such a string (*without*... | ```
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'
``` |
Python datetime to string without microsecond component | 7,999,935 | 112 | 2011-11-03T18:18:11Z | 8,000,106 | 9 | 2011-11-03T18:32:40Z | [
"python",
"datetime",
"datetime-format"
] | I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is `2011-11-03 11:07:04` (followed by `+00:00`, but that's not germane).
What's the best way to create such a string (*without*... | Yet another option:
```
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 11:31:28'
```
By default this uses local time, if you need UTC you can use the following:
```
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
'2011-11-03 18:32:20'
``` |
Python datetime to string without microsecond component | 7,999,935 | 112 | 2011-11-03T18:18:11Z | 8,000,168 | 8 | 2011-11-03T18:38:17Z | [
"python",
"datetime",
"datetime-format"
] | I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is `2011-11-03 11:07:04` (followed by `+00:00`, but that's not germane).
What's the best way to create such a string (*without*... | Here's the super lazy incorrect way to do it:
```
>>> import datetime
>>> unicode(datetime.datetime.now())[:-7]
u'2011-11-03 14:37:50'
``` |
conversion from float to Decimal in python-2.6: how to do it and why they didn't do it | 8,000,318 | 13 | 2011-11-03T18:51:09Z | 8,001,278 | 10 | 2011-11-03T20:16:54Z | [
"python",
"floating-point",
"decimal"
] | Direct conversion from float to Decimal was implemented in python-2.7, both in Decimal's constructor and with the Decimal.from\_float() classmethod.
Python-2.6 instead throws a TypeError suggesting to convert to string first:
```
TypeError: Cannot convert float to Decimal. First convert the float to a string
```
so... | Your workaround is not the RightWayToDoIt(tm) because it loses information. The lossless way to convert is shown in the recipe for float\_to\_decimal() shown in the [Decimal FAQ](http://docs.python.org/release/2.6.7/library/decimal.html#decimal-faq).
The reason we didn't include Decimal.from\_float in Python 2.6 is be... |
Trying to get one cell's values with MySQLdb | 8,001,109 | 2 | 2011-11-03T20:02:42Z | 8,001,147 | 9 | 2011-11-03T20:05:59Z | [
"python",
"mysql"
] | I am trying to get a single cell of values from MySQLdb, in Python. Here's my code:
```
fname = c.execute("""SELECT fname from employees WHERE user = %s;""", (useruname))
```
However what I get is "1L", which is not what I want - fname should contain a string, not a long integer.
Why would it do this? | The method [`execute`](http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb.cursors.BaseCursor-class.html#execute) "returns long integer rows affected, if any".
To get the value of fname, you need to fetch the results using for example [`fetchall`](http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/M... |
How do you check whether a number is divisible by another number (Python)? | 8,002,217 | 33 | 2011-11-03T21:37:37Z | 8,002,234 | 81 | 2011-11-03T21:39:03Z | [
"python",
"integer",
"modulus"
] | I need to test whether each number from 1 to 1000 is a multiple of 3 or a multiple of 5. The way I thought I'd do this would be to divide the number by 3, and if the result is an integer then it would be a multiple of 3. Same with 5.
How do I test whether the number is an integer?
here is my current code:
```
n = 0
... | You do this using the modulus operator, `%`
```
n % k == 0
```
evaluates true if and only if `n` is an exact multiple of `k`. In elementary maths this is known as the remainder from a division.
In your current approach you perform a division and the result will be either
* always an integer if you use integer divis... |
Difference between HDF5 file and PyTables file | 8,002,569 | 12 | 2011-11-03T22:13:40Z | 8,002,777 | 14 | 2011-11-03T22:35:37Z | [
"python",
"numpy",
"hdf5",
"pytables"
] | Is there a difference between `HDF5` files and files created by `PyTables`?
`PyTables` has two functions `.isHDFfile()` and `.isPyTablesFile()` suggesting that there
is a difference between the two formats.
I've done some looking around on Google and have gathered that PyTables is built on top of HDF, but I wasn't ab... | PyTables files are HDF5 files.
However, as I understand it, PyTables adds some extra metadata to the attributes of each entry in the HDF file.
If you're looking for a more "vanilla" hdf5 solution for python/numpy, have a look a `h5py`.
It's less database-like (i.e. less "table-like") than PyTables, and doesn't have ... |
Reading .csv files into Python lists | 8,003,858 | 8 | 2011-11-04T01:04:16Z | 8,003,871 | 10 | 2011-11-04T01:09:01Z | [
"python",
"csv"
] | I have a lot of .csv files in a directory and I'd like to open each of them in a loop within Python such that the first .csv is read into list[0] and the second .csv is read into list[1] and so on.
Unfortunately, while my code loops through all of the .csv files, it puts all the .csv files into list[0]. How can I modi... | inside the for loop, near the top, you have to refresh the list `rowdata`. otherwise you are adding to that one forever. have something like `rowdata = []` right after `print i`
```
def create_data_lists():
for symbol in symbols:
with open(symbol+'.csv', 'r') as f:
print symbol
rowdata = [... |
Is this possible to dynamically to generate an attribute in a python object? | 8,004,178 | 3 | 2011-11-04T02:09:55Z | 8,004,195 | 8 | 2011-11-04T02:13:34Z | [
"python",
"object",
"dynamic",
"python-3.x"
] | For example, the object only have two attributes, person object, in this example,
only have first name, and second name.
Is this possible to make a gender attribute on the fly? Thanks. | short answer: yes
```
class Person(object):
def __init__(self):
self.first_name = 'Will'
self.second_name = 'Awesome'
my_guy = Person()
my_guy.gender = "Male"
print(my_guy.gender)
```
will print `Male` |
How to split long regular expression rules to multiple lines in Python | 8,006,551 | 17 | 2011-11-04T08:24:45Z | 8,006,576 | 20 | 2011-11-04T08:28:01Z | [
"python",
"regex"
] | Is this actually doable? I have some very long regex pattern rules that are hard to understand because they don't fit into the screen at once. Example:
```
test = re.compile('(?P<full_path>.+):\d+:\s+warning:\s+Member\s+(?P<member_name>.+)\s+\((?P<member_type>%s)\) of (class|group|namespace)\s+(?P<class_name>.+)\s+is ... | You can split your regex pattern by quoting each segment. No backslashes needed.
```
test = re.compile(('(?P<full_path>.+):\d+:\s+warning:\s+Member'
'\s+(?P<member_name>.+)\s+\((?P<member_type>%s)\) '
'of (class|group|namespace)\s+(?P<class_name>.+)'
'\s+is not ... |
How to split long regular expression rules to multiple lines in Python | 8,006,551 | 17 | 2011-11-04T08:24:45Z | 8,006,611 | 12 | 2011-11-04T08:32:08Z | [
"python",
"regex"
] | Is this actually doable? I have some very long regex pattern rules that are hard to understand because they don't fit into the screen at once. Example:
```
test = re.compile('(?P<full_path>.+):\d+:\s+warning:\s+Member\s+(?P<member_name>.+)\s+\((?P<member_type>%s)\) of (class|group|namespace)\s+(?P<class_name>.+)\s+is ... | From <http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation>:
> Multiple adjacent string literals (delimited by whitespace), possibly
> using different quoting conventions, are allowed, and their meaning is
> the same as their concatenation. Thus, "hello" 'world' is equivalent
> to "hello... |
500 Error without anything in the apache logs | 8,007,176 | 33 | 2011-11-04T09:29:59Z | 8,007,802 | 45 | 2011-11-04T10:22:46Z | [
"python",
"apache",
"sqlalchemy",
"mod-wsgi",
"flask"
] | I am currently developing an application based on `flask`. It runs fine spawning the server manually using `app.run()`. I've tried to run it through `mod_wsgi` now. Strangely, I get a 500 error, and nothing in the logs. I've investigated a bit and here are my findings.
* Inserting a line like `print >>sys.stderr, "hel... | Turns out I was not completely wrong. The exception was indeed thrown by sqlalchemy. And as it's streamed to `stdout` by default, `mod_wsgi` silently ignored it (as far as I can tell).
To answer my main question: How to see the errors produced by the WSGI app?
It's actually very simple. Redirect your logs to `stderr`... |
Extract only a single directory from tar | 8,008,829 | 3 | 2011-11-04T11:54:11Z | 8,009,120 | 10 | 2011-11-04T12:22:46Z | [
"python",
"tar"
] | I am working on a project in python in which I need to extract only a subfolder of tar archive not all the files.
I tried to use
```
tar = tarfile.open(tarfile)
tar.extract("dirname", targetdir)
```
But this does not work, it does not extract the given subdirectory also no exception is thrown. I am a beginner in pyth... | Building on the second example from the [tarfile module documentation](https://docs.python.org/3.5/library/tarfile.html#examples), you could extract the contained sub-folder and all of its contents with something like this:
```
with tarfile.open("sample.tar") as tar:
subdir_and_files = [
tarinfo for tarinf... |
Function to close the window in Tkinter | 8,009,176 | 7 | 2011-11-04T12:28:54Z | 8,009,256 | 25 | 2011-11-04T12:36:10Z | [
"python",
"tkinter"
] | ```
import tkinter
class App():
def __init__(self):
self.root = Tkinter.Tk()
button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
button.pack()
self.root.mainloop()
def quit(self):
self.root.destroy
app = App()
```
How can I make my `quit` function to ... | ```
def quit(self):
self.root.destroy()
```
Add parentheses after `destroy` to call the method.
When you use `command=self.root.destroy` you pass the method to `Tkinter.Button` *without* the parentheses because you want `Tkinter.Button` to store the method for future calling, not to call it immediately when the b... |
How to read large file, line by line in python | 8,009,882 | 252 | 2011-11-04T13:26:29Z | 8,009,942 | 39 | 2011-11-04T13:31:42Z | [
"python"
] | I want to iterate over each line of an entire file. One way to do this is by reading the entire file, saving it to a list, then going over the line of interest. This method uses a lot of memory, so I am looking for an alternative.
My code so far:
```
for each_line in fileinput.input(input_file):
do_something(each... | Not clear with your code but I will give pointers to read a huge file in python.
Best method is to use [iter](http://docs.python.org/library/functions.html#iter) & [yield](http://docs.python.org/tutorial/classes.html#generators).
```
def readInChunks(fileObj, chunkSize=2048):
"""
Lazy function to read a file ... |
How to read large file, line by line in python | 8,009,882 | 252 | 2011-11-04T13:26:29Z | 8,009,974 | 11 | 2011-11-04T13:33:37Z | [
"python"
] | I want to iterate over each line of an entire file. One way to do this is by reading the entire file, saving it to a list, then going over the line of interest. This method uses a lot of memory, so I am looking for an alternative.
My code so far:
```
for each_line in fileinput.input(input_file):
do_something(each... | this is the canonical way of reading a file in python:
```
f = open(input_file)
for line in f:
do_stuff(line)
f.close()
```
it does not allocate a full list. It iterates over the lines. |
How to read large file, line by line in python | 8,009,882 | 252 | 2011-11-04T13:26:29Z | 8,010,133 | 706 | 2011-11-04T13:46:44Z | [
"python"
] | I want to iterate over each line of an entire file. One way to do this is by reading the entire file, saving it to a list, then going over the line of interest. This method uses a lot of memory, so I am looking for an alternative.
My code so far:
```
for each_line in fileinput.input(input_file):
do_something(each... | Nobody has given the correct, fully Pythonic way to read a file. It's the following:
```
with open(...) as f:
for line in f:
<do something with line>
```
The `with` statement handles opening and closing the file, including if an exception is raised in the inner block. The `for line in f` treats the file o... |
How to read large file, line by line in python | 8,009,882 | 252 | 2011-11-04T13:26:29Z | 32,589,529 | 10 | 2015-09-15T15:07:52Z | [
"python"
] | I want to iterate over each line of an entire file. One way to do this is by reading the entire file, saving it to a list, then going over the line of interest. This method uses a lot of memory, so I am looking for an alternative.
My code so far:
```
for each_line in fileinput.input(input_file):
do_something(each... | ## To strip newlines:
```
with open(file_path) as f:
for line_terminated in f:
line = line_terminated.rstrip('\n')
...
```
Because of [universal newline support](https://docs.python.org/2/library/functions.html#open) all text file lines will seem to be terminated with `'\n'`, whatever the terminat... |
Python re infinite execution | 8,010,005 | 17 | 2011-11-04T13:36:39Z | 8,010,073 | 49 | 2011-11-04T13:42:02Z | [
"python",
"regex"
] | I'm trying to execute this code :
```
import re
pattern = r"(\w+)\*([\w\s]+)*/$"
re_compiled = re.compile(pattern)
results = re_compiled.search('COPRO*HORIZON 2000 HOR')
print(results.groups())
```
But Python does not respond. The process takes 100% of the CPU and does not stop. I've tried this both o... | Your regex runs into [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html) because you have nested quantifiers (`([...]+)*`). Since your regex requires the string to end in `/` (which fails on your example), the regex engine tries all permutations of the string in the vain hope to find a ma... |
Subplots with dates on the x-axis | 8,010,549 | 9 | 2011-11-04T14:15:19Z | 8,025,617 | 11 | 2011-11-06T06:42:41Z | [
"python",
"matplotlib"
] | I'm having trouble using multiple subplots with dates on the x-axis.
I'm using the matplotlib example from [here](http://matplotlib.sourceforge.net/examples/api/date_demo.html). I've modified it to include another subplot (the data being plotted is the same). This is what I'm getting as output:
 function:
> Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared xaxes where the x-a... |
Cannot serialize datetime as JSON from Cherrypy | 8,011,081 | 2 | 2011-11-04T14:49:25Z | 8,011,865 | 9 | 2011-11-04T15:39:08Z | [
"python",
"json",
"datetime",
"cherrypy"
] | I'm attempting to send a list of records in response to an Ajax query. This works well unless the results include a datetime field when my process fails with the error `datetime.date(2011, 11, 1) is not JSON serializable`.
I attempted to combine the answer I found to a very [similar question](http://stackoverflow.com/... | I do the next in a similar case:
```
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
```
and at the call:
```
json.dumps(my_variable, cls=DecimalEncoder)
```
So in your case it s... |
Cannot serialize datetime as JSON from Cherrypy | 8,011,081 | 2 | 2011-11-04T14:49:25Z | 14,730,863 | 8 | 2013-02-06T13:57:49Z | [
"python",
"json",
"datetime",
"cherrypy"
] | I'm attempting to send a list of records in response to an Ajax query. This works well unless the results include a datetime field when my process fails with the error `datetime.date(2011, 11, 1) is not JSON serializable`.
I attempted to combine the answer I found to a very [similar question](http://stackoverflow.com/... | I got the same problem (Python 3.2, Cherrypy 3.2.2) and I solved it with the following code:
```
import cherrypy
import json
import datetime
class _JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.date):
return obj.isoformat()
return super().default(obj... |
open read and close a file in 1 line of code | 8,011,797 | 48 | 2011-11-04T15:34:25Z | 8,011,836 | 75 | 2011-11-04T15:37:41Z | [
"python",
"readfile"
] | Now I use:
```
pageHeadSectionFile = open('pagehead.section.htm','r')
output = pageHeadSectionFile.read()
pageHeadSectionFile.close()
```
But to make the code look better, I can do:
```
output = open('pagehead.section.htm','r').read()
```
When using the above syntax, how do I close the file to free up system resour... | You don't really have to close it - Python will do it automatically either during garbage collection or at program exit. But as @delnan noted, it's better practice to explicitly close it for various reasons.
So, what you can do to keep it short, simple and explicit:
```
with open('pagehead.section.htm','r') as f:
... |
open read and close a file in 1 line of code | 8,011,797 | 48 | 2011-11-04T15:34:25Z | 8,011,863 | 11 | 2011-11-04T15:38:56Z | [
"python",
"readfile"
] | Now I use:
```
pageHeadSectionFile = open('pagehead.section.htm','r')
output = pageHeadSectionFile.read()
pageHeadSectionFile.close()
```
But to make the code look better, I can do:
```
output = open('pagehead.section.htm','r').read()
```
When using the above syntax, how do I close the file to free up system resour... | Using CPython, your file will be closed immediately after the line is executed, because the file object is immediately garbage collected. There are two drawbacks, though:
1. In Python implementations different from CPython, the file often isn't immediately closed, but rather at a later time, beyond your control.
2. In... |
Python + Django + VirtualEnv + Windows | 8,012,956 | 17 | 2011-11-04T16:53:38Z | 13,038,526 | 15 | 2012-10-23T20:16:25Z | [
"python",
"windows",
"django",
"virtualenv"
] | I had some problem on installing python + virtualenv + django and need help.
System: Windows 7, 64b
What i do?
**1) Installed Python 2.7.2 (32bits)
2) Installed SetupTools (32 bits)
3) Installed VirtualEnv**
```
E:\APPZ\Console2>C:\Python27\Scripts\easy_install.exe virtualenv
```
**4) Created virtualenv:**
```
E:\... | I know this question is old and maybe not actual anymore for author. But as far as it appears at Google's top, I would leave the answer that helped me.
Basically the correct answer is [posted](http://stackoverflow.com/a/10070104/592377) for the similar [question](http://stackoverflow.com/questions/312549/no-module-nam... |
pip not working | 8,013,581 | 15 | 2011-11-04T17:42:46Z | 8,401,521 | 15 | 2011-12-06T14:29:05Z | [
"python",
"ubuntu-10.04",
"pip"
] | I am trying to install python-shapely with pip in Ubuntu 10.04. I got "Unknown or unsupported command 'install'" while I tried,
`user@desktop:~$ pip install Shapely`
I tried installing pip and got the following error:
```
user@desktop:~$ sudo apt-get install python-pip
Reading package lists... Done
Building dependen... | Did you install pip first, then get this error, then try to install python-pip?
If so, first remove pip (apt-get remove pip), then install python-pip instead and try again.
(I just had the same problem, not sure if python 2.7 uses pip and 2.6 uses python-pip? That might be the issue.) |
Elegant way to create thumbnails of images stored on s3 with ec2 and communicate with rails on finish? | 8,013,999 | 8 | 2011-11-04T18:20:04Z | 29,016,336 | 15 | 2015-03-12T17:22:38Z | [
"python",
"node.js",
"amazon-s3",
"amazon-ec2",
"aws-lambda"
] | OK, so a quick summary of my setup and what i want to accomplish:
1. I have a rails 2.3.5 server that runs my website. I have a flash application on my site where users can upload images directly to s3.
2. When an upload is completed, rails is notified.
3. At the point where the image is finished uploading to s3 and r... | for those like me who looked this up, AWS now offers [Lambda](http://docs.aws.amazon.com/lambda/latest/dg/welcome.html)
> AWS Lambda is a compute service that makes it easy for you to build
> applications that respond quickly to new information. AWS Lambda runs
> your code in response to events such as image uploads, ... |
How to make mysql connection that requires CA-CERT with sqlalchemy or SQLObject | 8,014,781 | 3 | 2011-11-04T19:32:55Z | 14,992,181 | 7 | 2013-02-20T23:53:12Z | [
"python",
"mysql",
"sqlalchemy",
"sqlobject"
] | I would like to connect to a MySQL database that requires ca-cert. I can do it with MySQLdb like below:
```
MySQLdb.connect(host = self.host,
port = self.port,
unix_socket = self.unix_socket,
user = self.user,
passwd = self... | To use SSL certs with SQLAlchemy and MySQLdb, use the following python code:
```
db_connect_string='mysql://<user>:<pswd>@<db server>:3306/<database>'
ssl_args = {'ssl': {'cert':'/path/to/client-cert',
'key':'/path/to/client-key',
'ca':'/path/to/ca-cert'}}
create_engine(db... |
How can I use Jinja with Twisted? | 8,015,272 | 3 | 2011-11-04T20:19:50Z | 8,017,567 | 15 | 2011-11-05T01:41:46Z | [
"python",
"orm",
"twisted",
"flask",
"jinja2"
] | I'm planning up a discussion software using Python with Twisted, Storm, and Jinja. The problem is that Jinja was not made for Twisted or asynchronous socket libraries, and the performance provided by using Twisted is why I don't plan on using Flask.
So, how can I have Twisted render webpages using Jinja? | You can render web pages using Jinja the same way you would use any other Python library in Twisted. You just call into it. This will work fine with Twisted, although you may run into performance issues if Jinja does something blocking. Note that it is *possible* to use blocking libraries with Twisted just fine, either... |
python unicode handling differences between print and sys.stdout.write | 8,016,236 | 8 | 2011-11-04T22:04:24Z | 8,017,093 | 11 | 2011-11-04T23:56:51Z | [
"python",
"python-2.7",
"unicode",
"stdout"
] | I'll start by saying that I've already seen this post: [Strange python print behavior with unicode](http://stackoverflow.com/questions/7013354/strange-python-print-behavior-with-unicode), but the solution offered there (using PYTHONIOENCODING) didn't work for me.
Here's my issue:
```
Python 2.6.5 (r265:79063, Apr 9 ... | This is due to a long-standing bug that was [fixed](http://hg.python.org/lookup/r84621) in python-2.7, but too late to be back-ported to python-2.6.
The documentation states that when unicode strings are written to a file, they should be converted to byte strings using [file.encoding](http://docs.python.org/library/st... |
Choosing GCC version when building ( setup.py ) | 8,016,520 | 3 | 2011-11-04T22:39:04Z | 8,016,961 | 9 | 2011-11-04T23:35:34Z | [
"python",
"gcc",
"distutils"
] | I am trying to build a python module (scikit.timeseries) using
```
python setup.py build
```
but it's erroring out like this :
```
/Versions/2.6/lib/python2.6/site-packages/numpy/core/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c'
gcc-4.0: scikits/timeseries/src/cseries.c
sh: gcc-4... | Try
```
export CC=/usr/bin/gcc
python setup.py build
``` |
sort a list of dictionary of dictionary in python | 8,017,345 | 3 | 2011-11-05T00:53:06Z | 8,017,371 | 9 | 2011-11-05T00:57:27Z | [
"python",
"list",
"dictionary",
"sorting"
] | I just want to sort by first\_name this list in python
```
list = [ { "profile" : { "first_name" : "a", "last_name" : "b" } } ,
{ "profile" : { "first_name" : "c", "last_name" : "d" } } ,
{ "profile" : { "first_name" : "e", "last_name" : "f" } } ]
``` | This should do it:
```
>>> sorted(lst, key=lambda x: x['profile']['first_name'])
``` |
sort a list of dictionary of dictionary in python | 8,017,345 | 3 | 2011-11-05T00:53:06Z | 8,018,433 | 7 | 2011-11-05T05:48:31Z | [
"python",
"list",
"dictionary",
"sorting"
] | I just want to sort by first\_name this list in python
```
list = [ { "profile" : { "first_name" : "a", "last_name" : "b" } } ,
{ "profile" : { "first_name" : "c", "last_name" : "d" } } ,
{ "profile" : { "first_name" : "e", "last_name" : "f" } } ]
``` | To sort the list itself, use:
```
lst.sort(key=lambda x: x['profile']['first_name'])
```
To keep `lst` unsorted and return a sorted list use:
```
sorted(lst, key=lambda x: x['profile']['first_name'])
``` |
Most efficient way to index words in a document? | 8,017,432 | 7 | 2011-11-05T01:09:55Z | 8,017,470 | 12 | 2011-11-05T01:20:02Z | [
"python",
"text",
"nlp"
] | This came up in another question but I figured it is best to ask this as a separate question. Give a large list of sentences (order of 100 thousands):
```
[
"This is sentence 1 as an example",
"This is sentence 1 as another example",
"This is sentence 2",
"This is sentence 3 as another example ",
"This is sentence 4"
... | Use database for storing values.
1. First **add all the sentences to one table** (they should have IDs). You may call it eg. `sentences`.
2. Second, **create table with words** contained within all the sentences (call it eg. `words`, give each word an ID), saving connection between sentences' table records and words' ... |
Python conversion madness | 8,018,645 | 7 | 2011-11-05T06:45:04Z | 8,018,681 | 11 | 2011-11-05T06:53:58Z | [
"python",
"syntax",
"for-loop",
"list-comprehension"
] | I have a code understanding problem related to python:
```
def convex_hull(pts):
"""Returns the points on the convex hull of pts in CCW order."""
for m in (2 ** (2 ** t) for t in xrange(len(pts))):
hulls = [_graham_scan(pts[i:i + m]) for i in xrange(0, len(pts), m)]
//more code
```
I can't figure out ... | To understand this code, you first need to understand [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) and [generator expressions](http://docs.python.org/tutorial/classes.html#generator-expressions). Here is a an example of a simple list comprehension:
```
>>> [str(i) for ... |
how to iterate through dictionary in a dictionary in django template? | 8,018,973 | 48 | 2011-11-05T08:08:12Z | 8,018,989 | 103 | 2011-11-05T08:12:17Z | [
"python",
"django",
"dictionary",
"django-templates"
] | My dictionary looks like this(Dictionary within a dictionary):
> {'0': {'chosen\_unit': , 'cost': Decimal('10.0000'),
> 'unit\_\_name\_abbrev': u'G', 'supplier\_*supplier': u"Steve's Meat
> Locker", 'price': Decimal('5.00'), 'supplier*\_address':
> u'No\r\naddress here', 'chosen\_unit\_amount': u'2', 'city\_*name':
> ... | Lets say your data is -
`data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }`
You can use the `data.items()` method to get the dictionary elements. Note, in django templates we do NOT put `()`. Also some users mentioned `values[0]` does not work, if that is the case then try `values.items`.
```
<table>
<tr>
... |
Changing a function implementation in Python | 8,020,159 | 5 | 2011-11-05T12:25:51Z | 8,020,264 | 8 | 2011-11-05T12:48:02Z | [
"python",
"function",
"metaprogramming"
] | I am writing a module that provides one function and needs an initialization step, however due to certain restrictions I need to initialize on first call, so I am looking for the proper idiom in python that would allow me to get rid of the conditional.
```
#with conditional
module.py
initialized = False
def function(*... | The nothing-fancy way (of the methods I post here, this is probably the best way to do it):
**module.py:**
```
def initialize():
print('initialize')
def do_the_thing(args):
print('doing things',args)
def function(args):
_function(args)
def firsttime(args):
global _function
initialize()
do_the_... |
Can I build a list, and sort it at the same time? | 8,021,314 | 10 | 2011-11-05T15:56:14Z | 8,021,332 | 13 | 2011-11-05T15:59:04Z | [
"python",
"list",
"sorting"
] | I'm working on a script for a piece of software, and it doesn't really give me direct access to the data I need. Instead, I need to ask for each piece of information I need, and build a list of the data I'm getting. For various reasons, I need the list to be sorted. It's very easy to just build the list once, and then ... | The short answer is: it's not worth it.
Have a look at [insertion sort](http://en.wikipedia.org/wiki/Insertion_sort). The worst-case running time is `O(n^2)` (average case is also quadratic). On the other hand, [Python's sort](http://corte.si//posts/code/timsort/index.html) (also known as [Timsort](http://en.wikipedia... |
Python: Converting from `datetime.datetime` to `time.time` | 8,022,161 | 26 | 2011-11-05T18:03:04Z | 8,022,196 | 9 | 2011-11-05T18:08:26Z | [
"python",
"time",
"calendar"
] | In Python, how do I convert a `datetime.datetime` into the kind of `float` that I would get from the `time.time` function? | Given a `datetime.datetime` object `dt`, you could use
```
(dt - datetime.datetime.utcfromtimestamp(0)).total_seconds()
```
Example:
```
>>> dt = datetime.datetime.now(); t = time.time()
>>> t
1320516581.727343
>>> (dt - datetime.datetime.utcfromtimestamp(0)).total_seconds()
1320516581.727296
```
Note that the `tim... |
Python: Converting from `datetime.datetime` to `time.time` | 8,022,161 | 26 | 2011-11-05T18:03:04Z | 8,022,223 | 20 | 2011-11-05T18:12:20Z | [
"python",
"time",
"calendar"
] | In Python, how do I convert a `datetime.datetime` into the kind of `float` that I would get from the `time.time` function? | ```
time.mktime(dt_obj.timetuple())
```
Should do the trick. |
Python: Converting from `datetime.datetime` to `time.time` | 8,022,161 | 26 | 2011-11-05T18:03:04Z | 8,022,340 | 22 | 2011-11-05T18:34:47Z | [
"python",
"time",
"calendar"
] | In Python, how do I convert a `datetime.datetime` into the kind of `float` that I would get from the `time.time` function? | It's not hard to use the time tuple method and still retain the microseconds:
```
>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2011, 11, 5, 11, 26, 15, 37496)
>>> time.mktime(t.timetuple()) + t.microsecond / 1E6
1320517575.037496
``` |
Python check for valid email address? | 8,022,530 | 81 | 2011-11-05T19:05:23Z | 8,022,584 | 131 | 2011-11-05T19:12:34Z | [
"python",
"regex",
"email-validation",
"email-address"
] | Is there a good way to check a form input using regex to make sure it is a proper style email address? Been searching since last night and everybody that has answered peoples questions regarding this topic also seems to have problems with it if it is a subdomained email address. | There is no point. Even if you can verify that the email address is syntactically valid, you'll still need to check that it was not mistyped, and that it actually goes to the person you think it does. The only way to do that is to send them an email and have them click a link to verify.
Therefore, a most basic check (... |
Python check for valid email address? | 8,022,530 | 81 | 2011-11-05T19:05:23Z | 8,022,711 | 15 | 2011-11-05T19:30:52Z | [
"python",
"regex",
"email-validation",
"email-address"
] | Is there a good way to check a form input using regex to make sure it is a proper style email address? Been searching since last night and everybody that has answered peoples questions regarding this topic also seems to have problems with it if it is a subdomained email address. | Email addresses are not as simple as they seem! For example, Bob\_O'Reilly+tag@example.com, is a valid email address.
I've had some luck with the lepl package (<http://www.acooke.org/lepl/>). It can validate email addresses as indicated in RFC 3696: <http://www.faqs.org/rfcs/rfc3696.html>
Found some old code:
```
im... |
Python check for valid email address? | 8,022,530 | 81 | 2011-11-05T19:05:23Z | 14,485,817 | 56 | 2013-01-23T17:34:09Z | [
"python",
"regex",
"email-validation",
"email-address"
] | Is there a good way to check a form input using regex to make sure it is a proper style email address? Been searching since last night and everybody that has answered peoples questions regarding this topic also seems to have problems with it if it is a subdomained email address. | The Python standard library comes with an e-mail parsing function: [`email.utils.parseaddr()`](http://docs.python.org/2/library/email.util.html#email.utils.parseaddr).
It returns a two-tuple containing the real name and the actual address parts of the e-mail:
```
>>> from email.utils import parseaddr
>>> parseaddr('f... |
Get key by value in dictionary | 8,023,306 | 189 | 2011-11-05T21:09:18Z | 8,023,329 | 134 | 2011-11-05T21:11:50Z | [
"python",
"dictionary"
] | I made a function which will look up ages in dictionary and show the matching name:
```
list = {'george':16,'amber':19}
search_age = raw_input("Provide age")
for age in list.values():
if age == search_age:
name = list[age]
print name
```
I know how to compare and find the age I just don't know how... | If you want both the name *and* the age, you should be using `.items()` which gives you key `(key, value)` tuples:
```
for name, age in mydict.items():
if age == search_age:
print name
```
You can unpack the tuple into two separate variables right in the `for` loop, then match the age.
You should also co... |
Get key by value in dictionary | 8,023,306 | 189 | 2011-11-05T21:09:18Z | 8,023,337 | 173 | 2011-11-05T21:13:09Z | [
"python",
"dictionary"
] | I made a function which will look up ages in dictionary and show the matching name:
```
list = {'george':16,'amber':19}
search_age = raw_input("Provide age")
for age in list.values():
if age == search_age:
name = list[age]
print name
```
I know how to compare and find the age I just don't know how... | There is none. `dict` is not intended to be used this way.
```
for name, age in list.iteritems():
if age == search_age:
print name
``` |
Get key by value in dictionary | 8,023,306 | 189 | 2011-11-05T21:09:18Z | 11,423,953 | 13 | 2012-07-11T00:35:40Z | [
"python",
"dictionary"
] | I made a function which will look up ages in dictionary and show the matching name:
```
list = {'george':16,'amber':19}
search_age = raw_input("Provide age")
for age in list.values():
if age == search_age:
name = list[age]
print name
```
I know how to compare and find the age I just don't know how... | ```
lKey = [key for key, value in lDictionary.iteritems() if value == lValue][0]
``` |
Get key by value in dictionary | 8,023,306 | 189 | 2011-11-05T21:09:18Z | 13,149,770 | 195 | 2012-10-31T00:56:34Z | [
"python",
"dictionary"
] | I made a function which will look up ages in dictionary and show the matching name:
```
list = {'george':16,'amber':19}
search_age = raw_input("Provide age")
for age in list.values():
if age == search_age:
name = list[age]
print name
```
I know how to compare and find the age I just don't know how... | ```
mydict = {'george':16,'amber':19}
print mydict.keys()[mydict.values().index(16)] # Prints george
```
Or in Python 3.x:
```
mydict = {'george':16,'amber':19}
print(list(mydict.keys())[list(mydict.values()).index(16)]) # Prints george
```
Basically, it separates the dictionary's values in a list, finds the positio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.