如何在python中将带有元组和字典的列表转换为字典

如何在python中将带有元组和字典的列表转换为字典,python,Python,我的清单如下: [(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'c

我的清单如下:

    [(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')]
我想将其转换为以下格式:

    {"profileDetails":{"customerCategory":{"masterCode":"PRECAT1"},
"identificationDetails":{"identificationDetail":
     [{"idType":{"masterCode":"PASS"}},
     {"idType":{"masterCode":"REGFORM"}}]},
"customerSubCategory":{"masterCode":"PRESCAT1"}},
"_id": "58872e99321a0c8633291b3f"}
我知道上面的结果包含元组、列表和字典以及所有unicode格式的数据


我需要将unicode转换为字符串和元组,并将列表转换为字典。如何在Python中实现这一点?

使用dict理解:

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'}}]}}}
{tup[0]: tup[1] for tup in lst if len(tup) == 2}
注意,因为我没有
ObjectId
,所以我用它的字符串参数替换了它

如果列表包含长度为1或大于2的元组,则可以使用try except来处理
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))
或者,如果您只想忽略这些元组,您可以通过dict理解检查长度:

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'}}]}}}
{tup[0]: tup[1] for tup in lst if len(tup) == 2}

如果您有一个元组字符串,可以使用
ast.literal\u eval
将字符串转换为元组对象。

使用dict理解:

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'}}]}}}
{tup[0]: tup[1] for tup in lst if len(tup) == 2}
注意,因为我没有
ObjectId
,所以我用它的字符串参数替换了它

如果列表包含长度为1或大于2的元组,则可以使用try except来处理
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))
或者,如果您只想忽略这些元组,您可以通过dict理解检查长度:

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'}}]}}}
{tup[0]: tup[1] for tup in lst if len(tup) == 2}

如果您有一个元组字符串,您可以使用
ast.literal\u eval
将字符串转换为元组对象。

只需将元组列表强制转换为
dict
,如下所示:

>>> dict(my_list)
将返回:

{'_id': '58872e99321a0c8633291b3f', 
 'profileDetails': {
      'customerSubCategory': {'masterCode': 'PRESCAT1'}, 
      'identificationDetails': {'identificationDetail': [
          {'idType': {'masterCode': 'PASS'}}, 
          {'idType': {'masterCode': 'REGFORM'}}
      ]}, 
  'customerCategory': {'masterCode': 'PRECAT1'}}
 }
这里,
my_list
是问题中提到的元组列表


当将格式为
[(x1,y1)、(x2,y2)]
的元组列表(或列表)类型转换为
dict
时,python解释器将创建格式为
{x1:y1,x2:y2}的dict对象
即元组第0个索引处的所有元素成为键,索引1处的元素成为结果dict的值。

只需键入将元组列表强制转换为dict,如下所示:

>>> dict(my_list)
将返回:

{'_id': '58872e99321a0c8633291b3f', 
 'profileDetails': {
      'customerSubCategory': {'masterCode': 'PRESCAT1'}, 
      'identificationDetails': {'identificationDetail': [
          {'idType': {'masterCode': 'PASS'}}, 
          {'idType': {'masterCode': 'REGFORM'}}
      ]}, 
  'customerCategory': {'masterCode': 'PRECAT1'}}
 }
这里,
my_list
是问题中提到的元组列表


当将格式为
[(x1,y1),(x2,y2)]
的元组列表(或列表)类型转换为
dict
时,python解释器创建格式为
{x1:y1,x2:y2}
的dict对象,即元组第0个索引处的所有元素成为键,索引1处的元素成为结果dict的值。

{i:j代表i,j在lst}
只是
dict(lst)
hi chris和kasramvd,谢谢你的回复,在我的情况下,它不起作用,当我尝试两种解决方案
{i:j代表i,j在lst}
dict(lst)
,我得到一个错误
ValueError:dictionary update sequence元素#0的长度为1;需要2
@SaradaAkurathi可能有些元组不包含2个元素(它们包含1个元素)kasramvd,没有,它有两个元素,当我将输入声明为变量并尝试时,它工作得很好,但是如果我将相同的输入作为方法的参数,并在方法内部尝试转换为字典,则错误是coming@SaradaAkurathi我不完全明白你的意思,函数的参数是一个字符串,它是h作为元组形式的数据*如果您有一个元组字符串,您可能需要考虑使用<代码> AST.MealAlviaEv>代码>,以便将字符串转换为Python对象。<代码> {i:j为i,j在LST } /代码>中只是<代码> DICT(LST)。hi chris and kasramvd,感谢您的回复,在我的情况下,当我尝试两种解决方案时,
{i:j for i,j in lst}
dict(lst)
,我得到一个错误
ValueError:dictionary update sequence元素#0的长度为1;需要2
@SaradaAkurathi可能有些元组不包含2个元素(它们包含1个元素)kasramvd,没有,它有两个元素,当我将输入声明为变量并尝试时,它工作得很好,但是如果我将相同的输入作为方法的参数,并在方法内部尝试转换为字典,则错误是coming@SaradaAkurathi我不完全明白你的意思,函数的参数是一个字符串,它是h作为元组形式的数据*如果您有一个元组字符串,您可能需要考虑使用<代码> AST.MetralAlviaE/COD>以将字符串转换为Python对象。Hi MunudIn,谢谢回答,这个解决方案对我来说是有效的,当我把输入输入变量时,意味着我将输入声明为“代码> JSONDATABOR= [(UrrPrimeDebug)”,{u'customerCategory':{u'masterCode':u'PRECAT1'}}]并将其转换为
print dict(jsondata)
但作为函数的参数时不起作用。您能帮助我吗,出了什么问题Hi moinuddin,我的代码如下所示:
def convert_to__dict(数据):
print dict(数据)
然后我得到了错误
ValueError:dictionary update sequence element#0的长度为1;2是必需的
。您能帮我找出哪里出了问题吗。您好,moinuddin,感谢您的回复,这个解决方案在我将输入放入变量时对我有效,这意味着我将输入声明为
jsondata=[(u'profileDetails',{u'customerCategory':{u'masterCode':u'PRECAT1'}}]
并将其转换为
print dict(jsondata)
但作为函数的参数时不起作用。您能帮助我吗,出了什么问题Hi moinuddin,我的代码如下所示:
def convert_to__dict(数据):
print dict(数据)
然后我得到了错误
ValueError:dictionary update sequence元素#0的长度为1;2是必需的
。您能告诉我哪里出了问题吗。