Read data from CSV file and transform from string to correct data-type, including a list-of-integer column

As the docs explain, the CSV reader doesn’t perform automatic data conversion. You have the QUOTE_NONNUMERIC format option, but that would only convert all non-quoted fields into floats. This is a very similar behaviour to other csv readers. I don’t believe Python’s csv module would be of any help for this case at all. As … Read more

Sort nested dictionary by value, and remainder by another value, in Python

Use the key argument for sorted(). It lets you specify a function that, given the actual item being sorted, returns a value that should be sorted by. If this value is a tuple, then it sorts like tuples sort – by the first value, and then by the second value. sorted(your_list, key=lambda x: (your_dict[x][‘downloads’], your_dict[x][‘date’]))

How does Python’s “super” do the right thing?

Change your code to this and I think it’ll explain things (presumably super is looking at where, say, B is in the __mro__?): class A(object): def __init__(self): print “A init” print self.__class__.__mro__ class B(A): def __init__(self): print “B init” print self.__class__.__mro__ super(B, self).__init__() class C(A): def __init__(self): print “C init” print self.__class__.__mro__ super(C, self).__init__() class … Read more

How to properly use python’s isinstance() to check if a variable is a number?

In Python 2, you can use the types module: >>> import types >>> var = 1 >>> NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType) >>> isinstance(var, NumberTypes) True Note the use of a tuple to test against multiple types. Under the hood, IntType is just an alias for int, etc.: >>> isinstance(var, (int, long, float, complex)) … Read more

Check if input is a list/tuple of strings or a single string

You can check if a variable is a string or unicode string with Python 3: isinstance(some_object, str) Python 2: isinstance(some_object, basestring) This will return True for both strings and unicode strings As you are using python 2.5, you could do something like this: if isinstance(some_object, basestring): … elif all(isinstance(item, basestring) for item in some_object): # … Read more

How can I obtain the image size using a standard Python class (without using an external library)?

Here’s a Python 3 script that returns a tuple containing an image height and width for .png, .gif and .jpeg without using any external libraries (i.e., what Kurt McKee referenced). It should be relatively easy to transfer it to Python 2. import struct import imghdr def get_image_size(fname): ”’Determine the image type of fhandle and return its … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)