arrays - Python convert a list of tuples to a list of nested dicts -


i have problem driving me crazy.

i'm programming in python , have list of tuples:

my_tuples = [     ('csrf_token', u'5bc7224ef8f71c8142b4bef1597883b049b83fee'),     ('fields-team', u'dsada'),     ('fields-year_from', u'dsa'),     ('fields-year_to', u'dsa'),     ('fields-description', u'dsa') ,     ('fields-team', u''),     ('fields-year_from', u''),     ('fields-year_to', u''),     ('fields-description', u'') ] 

i have transform list of tuples this:

 form_data = {      'csrf_token':u'5bc7224ef8f71c8142b4bef1597883b049b83fee',      'fields':[          {              'team': u'dsada',              'year_from': u'dsa',              'year_to': u'dsa',              'description': u'dsa'          },          {              'team': u'',              'year_from': u'',              'year_to': u'',              'description': u''          }      ]  } 

and have delete second dictionary because every key has empty value. final result be:

 form_data = {      'csrf_token':u'5bc7224ef8f71c8142b4bef1597883b049b83fee',      'fields':[          {              'team': u'dsada',              'year_from': u'dsa',              'year_to': u'dsa',              'description': u'dsa'          }      ]  } 

my 2 cents:

import collections  def transform(loft):     form_data = collections.defaultdict(list)     internal = {}     numfield = 0     t in my_tuples:         keys = t[0].split("-")         if len(keys) == 1:             form_data[keys[0]] = t[1]         else:             internal[keys[1]] = t[1]             if numfield == 3:                 numfield = -1                 form_data[keys[0]].append(internal)                 internal = {}             numfield += 1     return form_data  if __name__ == "__main__":      my_tuples = [         ('csrf_token', u'5bc7224ef8f71c8142b4bef1597883b049b83fee'),         ('fields-team', u'dsada'),         ('fields-year_from', u'dsa'),         ('fields-year_to', u'dsa'),         ('fields-description', u'dsa') ,         ('fields-team', u''),         ('fields-year_from', u''),         ('fields-year_to', u''),         ('fields-description', u'')     ]     trans = transform(my_tuples)     # cleanup     trans['fields'] = [f i, f in enumerate(trans['fields'])         if trans['fields'][i]['team'] != ''         , trans['fields'][i]['year_from'] != ''         , trans['fields'][i]['year_to'] != ''         , trans['fields'][i]['description'] != '']     print dict(trans) 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -