user5355171
user5355171

Reputation: 35

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?

Upvotes: 1

Views: 1969

Answers (2)

Tebe Tensing
Tebe Tensing

Reputation: 1286

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

Upvotes: 0

awesoon
awesoon

Reputation: 33651

You could pass an iterable of tuples to a dict:

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

Upvotes: 2

Related Questions