pythonic

Python Dictionary to URL Parameters

I am trying to convert a Python dictionary to a string for use as URL parameters. I am sure that there is a better, more Pythonic way of doing this. What is it? x = "" for key, val in {'a':'A', 'b':'B'}.items(): x += "%s=%s&" %(key,val) x = x[:-1] ...

Pythonic Comparison Functions

For the sake of simplicity, let's say I have a Person class in Python. This class has fields for firstname, lastname, and dob. class Person: def __init__(self, firstname, lastname, dob): self.firstname = firstname; self.lastname = lastname; self.dob = dob; In some situations I want to sort lists of Persons by lastname f...

Iterate over pairs in a list (circular fashion) in Python

The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first). I've thought about two unpythonic ways of doing it: def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] and: def pairs(lst): return zip(lst,lst[1:]+[lst[0]])...

Pythonic way of searching for a substring in a list

I have a list of strings - something like mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text'] I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar*. My current solution looks like this for...

oop instantiation pythonic practices

I've got the code below, and I was planning on making several classes all within the same "import". I was hoping to instantiate each class and get a return value with the widgets I'm making. This isn't really a PyQt question at all, more of a "good practices" question, as I'll have a class for each widget. Should I make functions th...

Python design patterns, cross importing

I am using Python for automating a complex procedure that has few options. I want to have the following structure in python. - One "flow-class" containing the flow - One helper class that contains a lot of "black boxes" (functions that do not often get changed). 99% of the time, I modify things in the flow-class so I only want code ther...

Finding set difference between two complex dictionaries

Hi, I have two dictionaries of the following structure: a) dict1 = {'a':[ [1,2], [3,4] ], 'b':[ [1,2],[5,6] ]} b) dict2 = {'a':[ [1,2], [5,6] ], 'b':[ [1,2],[7,8] ]} I need to find the set difference between each key in the dictionary i.e., dict1['a'] - dict2['a'] should return [3,4]. Any thought is appreciated. ...

Generating a list from complex dictionary

Him I have a dictionary dict1['a'] = [ [1,2], [3,4] ]. I need to generate a list out of this dictionary as l1 = [2, 4] i.e., a list out of the second element of each inner list. It can be a separate list or even the dictionary can be modified as dict1['a'] = [2,4]. Any idea would be appreciated. ...

Python generating Python

Ok, I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experimenting with it and...

String formatting

Hi, I have a list filter = ['a', 'b', 'c']. I need to frame the following string out of the list "item -a item -b item -c". Which is the most efficient way to do this? Usually the list filter contains 100 to 200 items and each would be of length 100 - 150. Wouldn't that lead to overflow? And what is the maximum length of the string supp...

Is it possible to intercept attribute getting/setting in ActionScript 3?

When developing in ActionScript 3, I often find myself looking for a way to achieve something similar to what is offered by python's __getattr__ / __setattr__ magic methods i.e. to be able to intercept attribute lookup on an instance, and do something custom. Is there some acceptable way to achieve this in ActionScript 3? In AS3 attrib...

Convert list of objects to a list of integers and a lookup table

To illustrate what I mean by this, here is an example messages = [ ('Ricky', 'Steve', 'SMS'), ('Steve', 'Karl', 'SMS'), ('Karl', 'Nora', 'Email') ] I want to convert this list and a definition of groups to a list of integers and a lookup dictionary so that each element in the group gets a unique id. That id should map t...

Pythonic way to return list of every n'th item in a larger list

Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...] Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line? ...

Which is more pythonic for array removal?

I'm removing an item from an array if it exists. Two ways I can think of to do this Way #1 # x array, r item to remove if r in x : x.remove( r ) Way #2 try : x.remove( r ) except : pass Timing it shows the try/except way can be faster (some times i'm getting:) 1.16225508968e-06 8.80804972547e-07 1.14314196588e-06 8.73...

Python switch order of elements

I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem: Permute the letters of a string pairwise, e.g. input: 'abcdefgh' output: 'badcfehg' ...

Python decorator to ensure that kwargs are correct

I have done a decorator that I used to ensure that the keyword arguments passed to a constructor are the correct/expected ones. The code is the following: from functools import wraps def keyargs_check(keywords): """ This decorator ensures that the keys passed in kwargs are the onces that are specified in the passed tuple. When applied...

Python ctypes: copying Structure's contents

I want to mimic a piece of C code in Python with ctypes, the code is something like: typedef struct { int x; int y; } point; void copy_point(point *a, point *b) { *a = *b; } in ctypes it's not possible to do the following: from ctypes import * class Point(Structure): _fields_ = [("x", c_int),("y", c_int)] def copy_point(a,...

How do I get fluent in Python?

Once you have learned the basic commands in Python, you are often able to solve most programming problem you face. But the way in which this is done is not really Python-ic. What is common is to use the classical c++ or Java mentality to solve problems. But Python is more than that. It has functional programming incorporated; many libra...

For list unless empty in python

I've been writing a lot of constructs like this the past couple of days: list = get_list() if list: for i in list: pass # do something with the list else: pass # do something if the list was empty Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). Python has simplified a lot...

Condense this Python statement without destroying readability

I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help. I use return codes to verify that my internal functions return successfully. For example (from internal library functions): result = some_function(arg1,arg2) if result != OK: return result or (from main script level): result = some_functio...