Surachit Sarkar
Surachit Sarkar

Reputation: 37

Defaultdict appending trick

I have a text file where elements are stored in two column like the following:

 a 1,a 3,a 4,b 1,b 2,b 3,b 4,c 1,c 2.... etc

The file contains two columns, one is the key a,b,c etc, and the other is the elements 1,2,3,4 etc.

I stored these items using defaultdict and appended them. The items in the default dict are:

defaultdict(<type 'list'>, `{'a': ['0', '1', '2', '3', '4'], 'c': ['1', '2'], 'b': ['1', '2', '3', '4']}`)

I used following command:

from collections import defaultdict
positions = defaultdict(list)

with open('test.txt') as f:
    for line in f:
       sob = line.split()
       key=sob[0]
       ele=sob[1]
       positions[key].append(ele)
    print positions

Upvotes: 0

Views: 404

Answers (1)

Hackaholic
Hackaholic

Reputation: 19733

insted of defaultdict you can use OrderedDict

from collections import OrderedDict
positions = OrderedDict()
with open('test.txt') as f:
    for line in f:
        key, ele = line.strip().split()
        positions[key] = positions.get(key, []) + [ele]
print positions

Upvotes: 1

Related Questions