I have a file whose structure in strictly generic terms is similar to the following.
keyname value is always going to contain the name of a data set identified by keywords and values. The keywords are always the same for each keyname and contain data which is unique to the keyname. In the simplest terms if I read it like
What I would like to do is build a dictionary in which each keyname has a value which is another dictionary made up of keywords and values. For example if I were to manually build it the dictionary would look like
allowing for access to whole keys, or individual data values like
This is ripe for iterating over the data and adding as I go, if it were a list I would append, but I don't use dictionaries very often and don't know how to add/append/insert data. What is the best way to do this?
Code:
keyname first keyword1 1.1 keyword2 1.2 keyword3 1.3 keyname second keyword1 2.1 keyword2 2.2 keyword3 2.3 keyname third keyword1 3.1 keyword2 3.2 keyword3 3.3
Code:
>>> f=open('/tmp/test.txt','r')
>>> d=f.readlines()
>>> for l in d:
... print l.split()
...
['keyname', 'first']
['keyword1', '1.1']
['keyword2', '1.2']
['keyword3', '1.3']
['keyname', 'second']
['keyword1', '2.1']
['keyword2', '2.2']
['keyword3', '2.3']
['keyname', 'third']
['keyword1', '3.1']
['keyword2', '3.2']
['keyword3', '3.3']
Code:
dict={'first':{'keyword1':1.1,'keyword2':1.2,'keyword3':1.3},'second':{'keyword1':2.1,'keyword2':2.2,'keyword3':2.3},'third':{'keyword1':3.1,'keyword2':3.2,'keyword3':3.3}}
Code:
>>> dict['second']
{'keyword3': 2.2999999999999998, 'keyword2': 2.2000000000000002, 'keyword1': 2.1000000000000001}
>>> dict['second']['keyword2']
2.2000000000000002
Comment