![]() |
VOOZH | about |
We are given a dictionary and a number K, our task is to extract the first K key-value pairs. This can be useful when working with large dictionaries where only a subset of elements is needed. For example, if we have: d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} and K = 2 then the expected output would be: {'a': 1, 'b': 2}
The most efficient way to extract the first K key-value pairs is by using itertools.islice(). This method is efficient as it doesn’t create an intermediate list but instead extracts the required elements directly. We pass d.items() into islice() which retrieves the first K elements and then convert the result into a dictionary.
{'a': 1, 'b': 2}
Explanation:
Another efficient way is using dictionary comprehension with enumerate(). The enumerate() function assigns an index to each key-value pair and we filter out only the first K items.
{'a': 1, 'b': 2}
Explanation:
A simple but less efficient method is to convert d.items() into a list and then slice the first K elements while this works fine for small dictionaries, it is not memory-efficient for large ones since it creates an intermediate list.
{'a': 1, 'b': 2}
Explanation: