![](/img/trans.png)
[英]How to convert a dictionary of tuples into a dictionary of lists (Python)?
[英]Convert dictionary of lists to dictionary of tuples
大家好,我是python的新手(如果这是一个简单的问题,请原谅我)并使用k-means算法进行多处理,但是我在数据格式方面遇到问题。 我有一个列表的字典,其格式如下:
{0: [122.0, 0.000209], 1: [125.0, 0.000419], 2: [127.0, 0.000233], 3: [120.0, 0.000209], 4: [126.0, 0.000336]}
但是我需要它成为元组的字典,因此它看起来像:
{0: (122.0, 0.000209), 1: (125.0, 0.000419), 2: (127.0, 0.000233), 3: (120.0, 0.000209), 4: (126.0, 0.000336)}.
我知道你可以使用该功能
tuple(list)
将列表转换为元组,但是我确定如何遍历字典并将每个条目更改为元组。 有人对如何执行此操作有任何建议吗? 任何帮助表示赞赏,谢谢。
天真的方法:
for key in dictionary:
dictionary[key] = tuple(dictionary[key])
或看起来更干净但又完全相同的方式:
for key, value in dictionary.iteritems():
dictionary[key] = tuple(value)
或将最后一次重铸为字典,以提高清洁度:
dictionary = {k: tuple(v) for k,v in dictionary.iteritems()}
应该足以满足此特定任务。
(在Python 3中,请使用dictionary.items()
而不是iteritems()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.