如何将复杂字典列表转换为字典?
问题分析与解决方案
你想要将外层列表替换为大括号的写法在Python中不合法,因为字典的语法要求是{键: 值}的键值对结构,直接{{...}}这种嵌套字典但没有键的写法会触发语法错误。
错误写法(无法运行)
data={ { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } }
正确的转换方式
根据你的需求,有两种常见的合法实现方式:
方式1:将列表中的字典作为某个键的值
如果需要保留外层字典结构,给内部字典指定一个键:
# 原数据 data=[ { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } ] # 转换后 data = {'data_item': data[0]}
转换后的结构:
{ 'data_item': { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } }
方式2:直接提取列表中的唯一字典
如果不需要外层额外的字典结构,直接取出列表里的元素:
# 原数据 data=[ { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } ] # 转换后 data = data[0]
转换后的结构:
{ 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] }
内容的提问来源于stack exchange,提问作者Pathia Nanto
相关产品推荐
相关产品推荐

