This post will discuss how to get a list of dictionary keys and values in Python.
1. Using List Constructor
The standard solution to get a view of the dictionary’s keys is using the dict.keys[] function. To convert this view into a list, you can use a list constructor, as shown below:
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} print[x] # ['A', 'B', 'C'] |
Download Run Code
You can also pass the dictionary to the list constructor, which is a shortcut to list[d.keys[]].
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} print[x] # ['A', 'B', 'C'] |
Download Run Code
Similarly, to get a list of the dictionary’s values, you can pass the view returned by the dict.values[] function to the list constructor.
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} |
Download Run Code
2. Using Iterable Unpacking Operator
Starting with Python 3.5, you can unpack the dictionary into a list literal like [*d]. This syntax was proposed in PEP 448.
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} print[x] # ['A', 'B', 'C'] |
Download Run Code
Alternatively, you can call the dict.keys[] function to make your code more explicit.
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} print[x] # ['A', 'B', 'C'] |
Download Run Code
To get a list of the dictionary’s values, you can call the dict.values[] function.
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} |
Download Run Code
3. Using Extended Iterable Unpacking
Another option in Python 3 is Extended Iterable Unpacking, which was introduced as part of PEP 3132. Now you can write *l, = dict, where l is an empty list and on the right-hand side is your dictionary.
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} print[x] # ['A', 'B', 'C'] |
Download Run Code
To get a list of the dictionary’s values, you can call the dict.values[] function on the right-hand side.
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} |
Download Run Code
That’s all about getting the list of dictionary keys and values in Python.
Thanks for reading.
Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and help us grow. Happy coding 🙂