简体   繁体   English

将列表字典转换为元组字典

[英]Convert dictionary of lists to dictionary of tuples

Hello everyone I am fairly new to python (so forgive me if this a simple question) and working on multiprocessing with a k-means algorithm but I am having an issue with data formatting. 大家好,我是python的新手(如果这是一个简单的问题,请原谅我)并使用k-means算法进行多处理,但是我在数据格式方面遇到问题。 I have a dictionary of lists formatted as so: 我有一个列表的字典,其格式如下:

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

but I need it to be a dictionary of tuples so it looks like: 但是我需要它成为元组的字典,因此它看起来像:

{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)}. 

I know you can use the function 我知道你可以使用该功能

tuple(list) 

to convert a list to a tuple but I am sure how to go about iterating through the dictionary and changing each entry to a tuple. 将列表转换为元组,但是我确定如何遍历字典并将每个条目更改为元组。 Does anyone have any advice on how to go about doing this? 有人对如何执行此操作有任何建议吗? Any help is appreciated thank you. 任何帮助表示赞赏,谢谢。

The naive way: 天真的方法:

for key in dictionary:
    dictionary[key] = tuple(dictionary[key])

or the slightly cleaner-looking but otherwise completely identical way: 或看起来更干净但又完全相同的方式:

for key, value in dictionary.iteritems():
    dictionary[key] = tuple(value)

or the last recast as a dictionary comprehension for even more cleanliness: 或将最后一次重铸为字典,以提高清洁度:

dictionary = {k: tuple(v) for k,v in dictionary.iteritems()}

should all suffice for this particular task. 应该足以满足此特定任务。

(In Python 3, use dictionary.items() rather than iteritems() ) (在Python 3中,请使用dictionary.items()而不是iteritems()

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

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