Python dictionary is a built-in 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.
Python dictionary to list
To convert a dictionary to a list in Python, use either dict.keys() or dict.values() or dict.items() method.
- 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 dictionary’s values 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 dictionary keys.
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 a built-in 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()
Python dict.items() is a built-in method that returns a view object that displays a list of dictionary’s (key, value) tuple pairs. The items() method is similar to the 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 key data values: value pairs from a dictionary.