formatting file

gry at ll.mit.edu gry at ll.mit.edu
Wed Apr 6 11:00:35 EDT 2005


SPJ wrote:
> I am new to python hence posing this question.
> I have a file with the following format:
>
> test1    1.1-1   installed
> test1    1.1-1   update
> test2    2.1-1   installed
> test2    2.1-2   update
>
> I want the file to be formatted in the following way:
>
> test1    1.1-1   1.1-2
> test2    2.1-1   2.1-2

For data that has a clear tree structure with keys, a quick solution
is often a dictionary, or dictionary of dictionaries.  The setdefault
idiom below is very handy for this sort of thing.  The test name
"test1"
is key to the top dict.  The operation "update" is the key to the sub
dictionary.  Setdefault returns the dict for the specified test, or a
new dict if there is none.

.d={}
.for line in open('tests.txt'):
.    test,version,operation = l.split()
.    d.setdefault(test,{})[operation] = version

.for test,d in d.items():
.    print test, d['installed'], d['update']

[BWT, your given test data appears to have been
 wrong "test1    1.1-1   update"; please be careful not to waste
 people's time who try to help...]

-- George




More information about the Python-list mailing list