社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

将python列表转换为字典,而不添加额外的花括号

the_martian • 5 年前 • 1513 次点击  

假设我有一个这样的列表:

alist = [{'key': 'value'}]

然后我把它转换成这样的字典

adict = dict(alist)

格式变为

{'{''key: 'value}'}

这使得我无法从字典中访问数据。是否有一种方法可以将列表转换为字典而不需要额外的“——括号和单引号?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38150
 
1513 次点击  
文章 [ 3 ]  |  最新文章 5 年前
Gro
Reply   •   1 楼
Gro    6 年前

如果您的目标是用键值对(或一组键值对)初始化Dictionary对象,为什么要首先使用列表?

你可以简单地写

adict = {'key': 'value', 'Hello': 'world' }

print(adict)

David Silveiro
Reply   •   2 楼
David Silveiro    6 年前

如果您首先通过交换大括号来构造您的列表,那么使用这个不会有任何问题:)

听写([('a',1),('b',2),('c',3)]

Sheldore
Reply   •   3 楼
Sheldore    6 年前

你可以使用索引 0 为了避免额外的 { } 大括号,因为字典可以作为 alist[0] . 而且,你不需要 dict 另外,因为您的列表内容已经是一个字典

adict = alist[0]

现在你得到了想要的行为

print (adict)
# {'key': 'value'}