[英]How to convert a list of tuples to a dictionary of dictionaries in Python?
[英]how to convert list with tuples and dictionaries to dictionary in 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'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中實現?
使用字典理解:
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'}}]}}}
請注意,由於我沒有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理解來檢查長度:
{tup[0]: tup[1] for tup in lst if len(tup) == 2}
如果您有一個元組字符串,則可以使用ast.literal_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的值 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.