from typing import Mapping


def subdict(d: Mapping, keys=None):
    """Gets a sub-dict from a Mapping ``d``, extracting only those keys that are both in
    ``keys`` and ``d``.
    Note that the dict will be ordered as ``keys`` are, so can be used for reordering
    a Mapping.

    >>> subdict({'a': 1, 'b': 2, 'c': 3, 'd': 4}, keys=['b', 'a', 'd'])
    {'b': 2, 'a': 1, 'd': 4}
    """
    return {k: d[k] for k in (keys or ()) if k in d}