How does Python dict.keys() Return a List and a Set?
dict.keys()
method in Python returns a dict_keys
object, a view of the dictionary's keys that is unique and unordered, similar to a set but not a true list or set. It behaves like a set in some ways but can be converted to a list for list-like behaviour. In this article, we will explore how Python dict.keys() return a list and a set.
Example:
d = {'a': 1, 'b': 2, 'c': 3}
# Obtaining keys
k = d.keys()
print("Keys:", k)
print(type(k))
Output
Keys: dict_keys(['a', 'b', 'c']) <class 'dict_keys'>
Explanation:
This
returns a view of the dictionary's keys.It
shows it as adict_keys
object, not a list or set.
Let's understand how it returns a list and a set, one by one, in detail.
Table of Content
Returning a List
dict.keys() returns a view that keeps the order of keys as they were added to the dictionary. Converting this view to list shows the keys in that same order, making it look like a list.
Example:
d = {'a': 1, 'b': 2, 'c': 3}
# Convert keys to a list
l = list(d.keys())
print(l)
Output
['a', 'b', 'c']
Explanation:
- This code gets a view of the dictionary's keys in the order they were added, then converts that view into list, keeping the same order.
Returning a Set
dict.keys()
method returns view that behaves like set, where keys are unique and unordered. By converting the keys to set, we can perform set operations like union and intersection, demonstrating the set-like behavior of the view.
Example:
d1 = {'a': 1, 'b': 2, 'c': 3}
# Convert keys to a set
s = set(d1.keys())
print(s)
Output
{'c', 'a', 'b'}
Explanation:
- The code converts the dictionary keys to a set, making them unique and unordered.