0

I'd like to read in a number of text files that have the following structure:

3 560
7 470
2 680
4 620
3 640
...

The first column specifies conditions of a behavioral experiment, the second column reaction times. What I'd like to do is to create an array/list for each condition that contains the reaction times for this condition only. I've previously used Perl for this. As there are many different conditions, I wanted to avoid writing many separate elsif statements and therefore used the condition name in the array name:

push(@{condition.${cond}}, $rt);  # $cond being the condition, $rt being the reaction time

For example, creating an array like this:

@condition3 = (560, 640,...);

As I got interested in Python, I wanted to see how I would accomplish this using Python. I found a number of answers discouraging the use of variables in variable names, but have to admit that from these answers I could not derive how I would create lists as described above without reverting to separate elif's for each condition. Is there a way to do this? Any suggestions would be greatly appreciated!

Thomas

2
  • Great! Thank you all very much for your quick and detailed help! I had not realized that it is possible to append values to existing keys in a dictionary, as all dictionary examples I had seen so far associated keys with only a single value. Commented Mar 30, 2012 at 22:26
  • 1
    Dictionaries only hold a single value for each key, but that single value can be a list. Commented Mar 30, 2012 at 22:48

4 Answers 4

3

A dictionary would be a good way to do this. Try something like this:

from collections import defaultdict

conditions = defaultdict(list)

for cond, rt in data:
    conditions[cond].append(rt)
Sign up to request clarification or add additional context in comments.

Comments

3

The following code reads the file data.txt with the format you described and computes a dictionary with the reaction times per experiment:

experiments = {}
with open('data.txt', 'r') as f:
    data = [l.strip() for l in f.readlines()]
for line in data:
    index, value = line.split()
    try:
        experiments[int(index)].append(value)
    except KeyError:
        experiments[int(index)] = [value]
print experiments
# prints: {2: ['680'], 3: ['560', '640'], 4: ['620'], 7: ['470']}

You can now access the reaction times per experiment using experiments[2], experiments[3], et cetera.

Comments

1

This is a perfect application for a dictionary, which is similar to a Perl hash:

data = {}
with open('data.txt') as f:
    for line in f:
        try:
            condition, value = map(int, line.strip().split())
            data.setdefault(condition, []).append(value)
        except Exception:
            print 'Bad format for line'

Now you can access your different conditions by indexing data:

>>> data
{2: [680], 3: [560, 640], 4: [620], 7: [470]}
>>> data[3]
[560, 640]

Comments

1

I am not sure about your question, as to why would you think about using elif conditions.

If you store a list of integers in a dictionary, the key being values of the first column a.k.a condition value, and its corresponding value a list of reaction times.

For example: The dict would be like:

conditions['3'] -> [560, 640, ...]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.