Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting tuple to dictionary in python

I am trying to convert a line of string to dictionary where i am facing an error. here is what i have and what i did:

line="nsd-1:quorum"
t=tuple(line.split(":"))
d=dict(t)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    d=dict(t)
ValueError: dictionary update sequence element #0 has length 5; 2 is required

Basically, what i want to achieve is to have a key value pair. So if i have set of values separated by a ":", i want to have it as a key whatever is before the colon and after the colon needs to be the value for the key. example: if i take the above string, i want "nsd-1" as my key and "quorum" as value.

Any help is appreciated. Thanks

like image 434
cool77 Avatar asked Dec 15 '22 08:12

cool77


1 Answers

Wrap it in a list:

>>> dict([t])
{'nsd-1': 'quorum'}

There's also no need to convert the return value of split to a tuple:

>>> dict([line.split(':')])
{'nsd-1': 'quorum'}
like image 102
timgeb Avatar answered Jan 01 '23 17:01

timgeb