简体   繁体   中英

how to convert list with tuples and dictionaries to dictionary in python

I have a list like below:

    [(u'profileDetails', {u'customerCategory': {u'masterCode': u'PRECAT1'},
 u'identificationDetails': {u'identificationDetail':
            [{u'idType': {u'masterCode': u'PASS'}}, 
            {u'idType': {u'masterCode': u'REGFORM'}}]}, 
u'customerSubCategory': {u'masterCode': u'PRESCAT1'}}), 
    (u'_id', u'58872e99321a0c8633291b3f')]

I want to convert this as below:

    {"profileDetails":{"customerCategory":{"masterCode":"PRECAT1"},
"identificationDetails":{"identificationDetail":
     [{"idType":{"masterCode":"PASS"}},
     {"idType":{"masterCode":"REGFORM"}}]},
"customerSubCategory":{"masterCode":"PRESCAT1"}},
"_id": "58872e99321a0c8633291b3f"}

I understood the result above has tuples, lists and dictionaries and all the data in unicode format.

I need to convert unicode to string and tuples and list to dictionary. How can I achieve this in Python?

Use a dict comprehension:

In [2]: lst = [(u'profileDetails', {u'customerCategory': {u'masterCode': u'PRECAT1'}, u'identificationDetails': {u'identificationDetail': [{u'idType': {u'masterCode': u'PASS'}}, {u'idType': {u'masterCode': u'REGFORM'}}]}, u'customerSubCategory': {u'masterCode': u'PRESCAT1'}}), 
   ...: (u'_id', '58872e99321a0c8633291b3f')]

In [3]: {i: j for i, j in lst}
Out[3]: 
{'_id': '58872e99321a0c8633291b3f',
 'profileDetails': {'customerCategory': {'masterCode': 'PRECAT1'},
  'customerSubCategory': {'masterCode': 'PRESCAT1'},
  'identificationDetails': {'identificationDetail': [{'idType': {'masterCode': 'PASS'}},
    {'idType': {'masterCode': 'REGFORM'}}]}}}

Note that since I didn't have the ObjectId I replaced it with its string argument.

If your list is contain tuples with length 1 or more than 2, you can use a try-except in order to handle the ValueError :

def dict_creator(my_list):
    for tup in my_list:
        try:
            key, value = tup
        except ValueError:
            # do what you want with tup
        else:
            yield key, value

final_dict = dict(dict_creator(my_list))

Or if you just want to ignore those tuples you can check the length through the dict comprehension:

{tup[0]: tup[1] for tup in lst if len(tup) == 2}

In case you have a string of tuple you can use ast.literal_eval in order to convert the string to tuple object.

Just type-cast the list of tuples to dict as:

>>> dict(my_list)

which will return:

{'_id': '58872e99321a0c8633291b3f', 
 'profileDetails': {
      'customerSubCategory': {'masterCode': 'PRESCAT1'}, 
      'identificationDetails': {'identificationDetail': [
          {'idType': {'masterCode': 'PASS'}}, 
          {'idType': {'masterCode': 'REGFORM'}}
      ]}, 
  'customerCategory': {'masterCode': 'PRECAT1'}}
 }

Here, my_list is the list of tuples mentioned in the question.

When list of tuples (or list) in the form [(x1, y1), (x2, y2)] is type-casted to dict , python's interpreter creates a dict object of the format {x1: y1, x2: y2} ie all the elements at the 0th index of the tuple becomes key and the elements at the index 1 becomes value to the resultant dict.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM