I have three pieces of data that I need to nest in a dictionary using python
:
- ID (can be repeted)
- Date (of action - can be repeted)
- actions (lists of words that are associated to an ID and a date)
Example of data (tab-separated):
UID DATE ACTIONS
abc123 12/25/2016 break, pullover
abc123 12/25/2016 stop
abc123 10/15/2015 break, pullover, turn
def456 6/14/2015 turn, wash, skid
def456 11/24/2016 stop, wash, pullover, break
ghi789 2/12/2015 pullover, stop
CODE - revised with @moogle comments
from collections import defaultdict
date = ['12/25/16','12/25/16','10/15/2015','6/14/2015','11/24/2016','2/12/2015']
uid = ['abc123','abc123', 'abc123','def456', 'def456', 'ghi789']
action = [['break', 'pullover'],['stop'],['break','pullover','turn'],['turn','wash','skid'],['stop','wash','pullover','break'],['pullover','stop']]
d = defaultdict(list)
for uid, date, action in zip(uid, date, action):
d[id].append((date,action))
print dict(d)
DESIRED OUTPUT
The desired output is a nested dictionary of lists.
Where the parent key
is the ID and the parent value
is nested dictionaries in which the nested key
is the date and the nested value
is a list of lists (actions).
current actual output
{'ghi789': [('2/12/2015', ['pullover', 'stop'])], 'def456': [('6/14/2015', ['turn', 'wash', 'skid']), ('11/24/2016', ['stop', 'wash', 'pullover', 'break'])], 'abc123': [('12/25/16', ['break', 'pullover']), ('12/25/16', ['stop']), ('10/15/2015', ['break', 'pullover', 'turn'])]}
**desired output**
{'abc123':[{'12/25/2016':[['break', 'pullover'],['stop']]}, {'10/15/2015':[['break','pullover','turn']]}],'def456':[{'6/14/2015':[['turn','wash','skid'],['stop','wash','pullover','break']},'ghi789':{'2/12/2915':[['pullover','stop']]}]}
I tried to obtain the above output with the above code, which I adapted from HERE and looked up HERE. However, I continuosuly am getting errors. I think it has to do with the fact that I am trying to nest in the value a list of lists, and I am unsure what direction to go in to fix it.