简体   繁体   中英

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:

TypeError: cannot convert dictionary update sequence element #0 to a sequence

How can I resolve it?

You could pass an iterable of tuples to a dict :

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

Use 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']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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