Reputation: 33
Ok, so I have read in a text file from a .txt file that came in the format as such:
home school 5
home office 10
home store 7
school store 8
office school 4
END OF FILE
I then turned it into a two dimensional list in python and it looks something like:
[['home', 'school', '5'], ['home','office','10'],['home','store','7'],
['school','store','8'], ['office','school','4']]
But the way that I would really like it is to be more in dictionary format such as:
{'home': {'school': 5, 'office': 10, 'store': 7},
'school': {'store': 8},
'office': {'school': 4}}
That format looks a lot better and is easier to read. The data that I have is lot more in detail but this is simple version. I have read my text file as follows:
myFileOpen = open(myInputFile, 'r')
myMap = myFileOpen.readlines()[:-1]
#Format the list, each line becomes a list in a greater list
myMap = [i.split('\n')[0] for i in myMap]
myMap = [i.split(' ') for i in myMap]
If anyone can help explain how to this I'd be very grateful! Thank you!
Upvotes: 2
Views: 7352
Reputation: 137320
The code may look like this:
result = {}
for item in data:
result.setdefault(item[0], {}).update({item[1]: item[2]})
Proof with whole code: http://ideone.com/8XUA41
Upvotes: 2
Reputation: 3098
And the hack answer goes to:
txt =\
'''
home school 5
home office 10
home store 7
school store 8
office school 4
'''
txt = txt.strip()
gs = [line.split(" ") for line in txt.split("\n")]
ts = {}
[ts.setdefault(x, {}).setdefault(y, z) for (x, y, z) in gs]
print ts
Upvotes: 1
Reputation: 59974
It's messy, but it works with a defaultdict:
>>> from collections import defaultdict
>>> L = [['home', 'school', '5'], ['home', 'office', '10'], ['home', 'store', '7'], ['school', 'store', '8'], ['office', 'school', '4']]
>>> d = defaultdict(list)
>>> for i in L:
... d[i[0]].append(i[1:])
...
>>> {k: dict(v) for k, v in d.items()} # Or d.iteritems with python 2.x
{'home': {'school': '5', 'store': '7', 'office': '10'}, 'school': {'store': '8'}, 'office': {'school': '4'}}
I'm not that experienced with using defaultdicts, so there's probably a better way.
Upvotes: 0
Reputation: 298156
Skip the intermediate list and just do it all at once:
d = {}
with open(myInputFile, 'r') as handle:
for line in handle:
if line == 'END OF FILE':
continue
key1, key2, value = line.split()
if key1 not in d:
d[key1] = {}
d[key1][key2] = int(value)
You could further condense that last part into:
d.setdefault(key1, {})[key2] = int(value)
Upvotes: 1