How to index into a dictionary?

Dictionaries are unordered in Python versions up to and including Python 3.6. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can create a list of keys for a dictionary d using keys = list(d), and then access keys in the list by index keys[i], …

Read more

Best way to replace multiple characters in a string?

Replacing two characters I timed all the methods in the current answers along with one extra. With an input string of abc&def#ghi and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: text.replace(‘&’, ‘\&’).replace(‘#’, ‘\#’). Timings for each function: a) 1000000 loops, best of 3: 1.47 μs per …

Read more

pg_config executable not found

I am having trouble installing psycopg2. I get the following error when I try to pip install psycopg2: But the problem is pg_config is actually in my PATH; it runs without any problem: I tried adding the pg_config path to the setup.cfg file and building it using the source files I downloaded from their website (http://initd.org/psycopg/) and I get the following …

Read more

use np.random.multinomial() in python

I have a task to randomly chose 100 element from a population of alpha list [a,b,c,d] with corresponding frequency (probability) [0.1, 0.3, 0.2, 0.4]. There are many different ways to do it. But here I want what returned after this function call (suppose there is one) is a list of the number of elements chosen. …

Read more

Setting Django up to use MySQL

MySQL support is simple to add. In your DATABASES dictionary, you will have an entry like this: You also have the option of utilizing MySQL option files, as of Django 1.7. You can accomplish this by setting your DATABASES array like so: You also need to create the /path/to/my.cnf file with similar settings from above With this new method of connecting in Django …

Read more