How to Convert Python Dictionary to List
Python dictionary is an inbuilt data type that can save data differently from lists or arrays. It stores the data in the key-value pairs. Dictionaries are not sequences, so they can’t be indexed by the range of numbers; rather, they are indexed by the series of keys.
Convert Python Dictionary to List
Python dictionary has three methods that can convert the elements of the dictionary to a list.
- dict.keys(): The keys() method returns a view object that contains the keys of the dictionary as a list.
- dict.values(): The values() method returns a view object that contains the values of the dictionary as a list.
- dict.items(): The items() method returns a view object that displays a list of dictionary’s (key, value) tuple pairs.
Python dict.keys()
Let’s define a dictionary and apply the keys() method to get the list of all the keys of the dictionary.
sabrina = { "witch": "Sabrina Spellman", "warlock": "Nicholas Scratch", "darklord": "Lucifer Morningstar", } dict_keys = sabrina.keys() print(dict_keys) print(type(dict_keys))
Output
dict_keys(['witch', 'warlock', 'darklord']) <class 'dict_keys'>
The view object will reflect any changes done to the dictionary.
Python dict.values()
The dict.values() is an inbuilt function that returns a view object that displays a list of all the values in the dictionary.
sabrina = { "witch": "Sabrina Spellman", "warlock": "Nicholas Scratch", "darklord": "Lucifer Morningstar", } dict_values = sabrina.values() print(dict_values) print(type(dict_values))
Output
dict_values(['Sabrina Spellman', 'Nicholas Scratch', 'Lucifer Morningstar']) <class 'dict_values'>
The values() function also returns a view object that displays the list of all the values.
Python dict.items()
The dict.items() method in Python returns a view object that displays a list of dictionary’s (key, value) tuple pairs. The items() method is similar to the dictionary’s viewitems() method in Python 2.7.
sabrina = { "witch": "Sabrina Spellman", "warlock": "Nicholas Scratch", "darklord": "Lucifer Morningstar", } data = sabrina.items() print(data) print(type(data))
Output
dict_items([('witch', 'Sabrina Spellman'), ('warlock', 'Nicholas Scratch'), ('darklord', 'Lucifer Morningstar')]) <class 'dict_items'>
That’s it. The output of the code above should be the data values of the key: value pairs from a dictionary.