简体   繁体   English

在python中将元组转换为字典

[英]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. 例如:如果我使用上面的字符串,我想要“nsd-1”作为我的键,“quorum”作为值。

Any help is appreciated. 任何帮助表示赞赏。 Thanks 谢谢

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: 也没有必要将split的返回值转换为元组:

>>> dict([line.split(':')])
{'nsd-1': 'quorum'}

t放在一个空列表中,如下所示:

d=dict([t])

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

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