Reputation: 762
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. 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.
Upvotes: 2
Views: 116
Reputation: 9846
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()
)
Upvotes: 5