easy +8 pts

Common Keys of Two Dictionaries

Return a list of keys that appear in both dictionaries, sorted alphabetically.

Write a function `common_keys(dict1, dict2)` that takes two dictionaries and returns a list of keys that are present in **both** dictionaries. The result should be sorted in ascending (lexicographic) order. If there are no common keys, return an empty list. The values of the dictionaries do not matter; only the keys are compared. The input dictionaries may have keys of any hashable type, but the returned list should contain the keys as they are (their natural order when sorting). For example, if dict1 = {'a': 1, 'b': 2} and dict2 = {'b': 3, 'c': 4}, the function returns ['b'].

Constraints

The dictionaries contain hashable keys only. The number of keys in each dictionary is between 0 and 10^5. The function should run in O(n + m) time and O(min(n, m)) auxiliary space, where n and m are the numbers of keys in the input dictionaries.

Example

>>> common_keys({'a': 1, 'b': 2}, {'b': 3, 'c': 4})
['b']
>>> common_keys({'x': 100, 'y': 200}, {'y': 1, 'z': 2})
['y']
>>> common_keys({'a': 1}, {'b': 2})
[]
>>> common_keys({}, {'a': 1})
[]
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use the keys() method to get views of the keys.
You can use set intersection or a dictionary membership check.
Don't forget to sort the final list.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.