Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert dictionary into tuple

How do I convert a dictionary into a tuple? Below is my dynamic dictionary.

genreOptions = GenreGuideServiceProxy.get_all_genres();
genreDictionary = {};
    for genre in genreOptions:
        genreDictionary[genre.name] = genre.name;
like image 589
James Avatar asked Apr 05 '11 21:04

James


People also ask

Can we convert dictionary to tuple in Python?

Use the items() Function to Convert a Dictionary to a List of Tuples in Python. The items() function returns a view object with the dictionary's key-value pairs as tuples in a list. We can use it with the list() function to get the final result as a list.

Can we convert dictionary to list in Python?

Python's dictionary class has three methods for this purpose. The methods items(), keys() and values() return view objects comprising of tuple of key-value pairs, keys only and values only respectively. The in-built list method converts these view objects in list objects.


2 Answers

tuples = genreDictionary.items()

See http://docs.python.org/library/stdtypes.html#dict.items

like image 53
Spike Avatar answered Nov 15 '22 00:11

Spike


Do you want to make (key, value) pairs? Here is code to generate a list of (key, value) tuples...

thelist = [(key, genreOptions[key]) for key in genreOptions]

Ahh I see there is a more efficient answer above...

thelist = genreDictionary.items()

But I want to include the list comprehension example anyways :)

like image 26
2rs2ts Avatar answered Nov 15 '22 00:11

2rs2ts