简体   繁体   English

在python中将元组转换为字典

[英]Convert tuple to dictionary in python

I have a tuple as follows: 我有一个元组,如下所示:

(1, ['a', 'b', 'c'])

How can I convert such tuple into the following dictionary? 如何将这样的元组转换为以下字典?

{1: ['a', 'b', 'c’]}`

My actual tuple look like this: 我的实际元组如下所示:

a = (0, ['http://www.armslist.com/posts/2997703/pittsburgh-pennsylvania-handguns-for-sale--80--1911-frame', 'http://www.armslist.com/posts/4240186/racine-wisconsin-rifles-for-sale--stainless-winchester-m70-300wsm'])

When I am trying to convert it to a dictionary using dict(a) it is giving an error: 当我尝试使用dict(a)将其转换为字典时,出现错误:

TypeError: cannot convert dictionary update sequence element #0 to a sequence TypeError:无法将字典更新序列元素#0转换为序列

How can I resolve it? 我该如何解决?

You could pass an iterable of tuples to a dict : 您可以将可迭代的元组传递给dict

In [22]: dict([(1,['a','b','c'])])
Out[22]: {1: ['a', 'b', 'c']}

Use dict([a]) 使用dict([a])

In[56]: a=(0, ['http://www.armslist.com/posts/2997703/pittsburgh-pennsylvania-handguns-for-sale--80--1911-frame', 'http://www.armslist.com/posts/4240186/racine-wisconsin-rifles-for-sale--stainless-winchester-m70-300wsm'])
In[57]: dict([a])
Out[57]: 
{0: ['http://www.armslist.com/posts/2997703/pittsburgh-pennsylvania-handguns-for-sale--80--1911-frame',
  'http://www.armslist.com/posts/4240186/racine-wisconsin-rifles-for-sale--stainless-winchester-m70-300wsm']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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