Reputation: 617
SO,
Having a case of the Monday's and none of my references are helping me out.
I have a file formatted like this:
x1 y1 z1
x1 y2 z2
x2 y3 z3
I would like to make a dictionary formatted like this: {x1: [[y1, z1], [y2,z2]], x2: [y3,z3]} but I'm getting stuck on an efficient way to do this. Help?
Upvotes: 0
Views: 880
Reputation: 134621
You can do this:
result = { }
for line in lines:
terms = line.split()
result.setdefault(terms[0], []).append(terms[1:])
Upvotes: 0
Reputation: 17771
I'm going to say you start with a string
data_str = """x1 y1 z1
x1 y2 z2
x2 y3 z3"""
Then you'll have
data_list = [d.split() for d in data_str.splitlines()] # [['x1', 'y1', 'z1'], ['x1', 'y2', 'z2'], ['x2', 'y3', 'z3']]
Then create a defaultdict
from collections import defaultdict
data_dict = defaultdict(list)
for data_row in data_list: # E.g., data_row = ['x1', 'y1', 'z1']
data_dict[data_row[0]].append(data_row[1:])
print data_dict # defaultdict(<type 'list'>, {'x2': [['y3', 'z3']], 'x1': [['y1', 'z1'], ['y2', 'z2']]})
Upvotes: 4
Reputation: 26281
d={}
for line in file:
split = line.strip().split(" ")
if not d.has_key(split[0]): d[split[0]] = []
d[split[0]].append(split[1:])
Upvotes: 0
Reputation: 70239
You could do something like this:
def makeKeyValuePair(tokens):
return tokens[0], tokens[1:]
print dict(makeKeyValuePair(line.rstrip().split()) for line in fileObject)
It creates a dictionary from key-value pairs, which in turn are extracted from each line. This of course assumes that x1, y1 and so on don't contain spaces.
As delnan pointed out, you might have the case of duplicate keys, depending on your use case. That means you'll only get values from the last line with that key. To work around this, one could use a defaultdict
:
from collections import defaultdict
d = defaultdict(list)
for line in fileObject:
tokens = line.rstrip().split()
d[tokens[0]].append(tokens[1:])
Upvotes: 1