How to get a dictionary within a dictionary in python -


i have data in text file in format given below:-

monday     maths   100  95  65  32  23  45  77  54  78  88  45  67  89 tuesday    science 45   53  76  78  54  78  34  99  55  100 45  56 78 wednesday  english 43   45  56  76  98  34  65  34  45  67  76  34  98 

i want write python code produce output this:-

{ 'monday': {'maths': [100  95  65  32  23  45  77  54  78  88  45  67  89},  'tuesday': {'science':45   53  76  78  54  78  34  99  55  100 45  56 78},  'wednesday': {'english': 43   45  56  76  98  34  65  34  45  67  76  34  98} } 

here snippet:

fo = open('c:\\users\\aman\\documents\\dataval.txt','r') data = fo.readlines()  mydict = {} li = [] in range(len(data)):     row = data[i].split('\t')     timekey = row[0]     type = row[1]     if mydict.has_key(timekey):         li = mydict[timekey]         li.append(type)         mydict[timekey] = li     else:         li = []         li.append(type)         mydict[timekey] = li print mydict 

this gives me output like:-

{'monday': ['maths', 'science', 'english']}

but want output mentioned above.

can help?

here solution:

  dic = dict()   open('txt', 'r') fh:      l in fh.readlines():           try:               lines = l.split()               day, sub, num = lines[0], lines[1], [int(x) x in lines[2:]]               dic.setdefault(day, {})               dic[day][sub] = num           except exception er:               print er   print dic 

output:

 {'tuesday': {'science': [45, 53, 76, 78, 54, 78, 34, 99, 55, 100, 45, 56, 78]},    'wednesday': {'english': [43, 45, 56, 76, 98, 34, 65, 34, 45, 67, 76, 34, 98]},   'monday':  {'maths': [100, 95, 65, 32, 23, 45, 77, 54, 78, 88, 45, 67, 89]}} 

let me know if works you.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -