Get list of dictionary keys and values in Python
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:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} x = list(d.keys()) print(x) # ['A', 'B', 'C'] |
You can also pass the dictionary to the list constructor, which is a shortcut to list(d.keys()).
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} x = list(d) print(x) # ['A', 'B', 'C'] |
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.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} x = list(d.values()) print(x) # [1, 2, 3] |
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.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} x = [*d] print(x) # ['A', 'B', 'C'] |
Alternatively, you can call the dict.keys() function to make your code more explicit.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} x = [*d.keys()] print(x) # ['A', 'B', 'C'] |
To get a list of the dictionary’s values, you can call the dict.values() function.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} x = [*d.values()] print(x) # [1, 2, 3] |
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.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} *x, = d print(x) # ['A', 'B', 'C'] |
To get a list of the dictionary’s values, you can call the dict.values() function on the right-hand side.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} *x, = d.values() print(x) # [1, 2, 3] |
That’s all about getting the list of dictionary keys and values in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)