xref: /aosp_15_r20/external/bazel-skylib/lib/dicts.bzl (revision bcb5dc7965af6ee42bf2f21341a2ec00233a8c8a)
1# Copyright 2017 The Bazel Authors. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#    http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Skylib module containing functions that operate on dictionaries."""
16
17def _add(*dictionaries, **kwargs):
18    """Returns a new `dict` that has all the entries of the given dictionaries.
19
20    If the same key is present in more than one of the input dictionaries, the
21    last of them in the argument list overrides any earlier ones.
22
23    This function is designed to take zero or one arguments as well as multiple
24    dictionaries, so that it follows arithmetic identities and callers can avoid
25    special cases for their inputs: the sum of zero dictionaries is the empty
26    dictionary, and the sum of a single dictionary is a copy of itself.
27
28    Args:
29      *dictionaries: Zero or more dictionaries to be added.
30      **kwargs: Additional dictionary passed as keyword args.
31
32    Returns:
33      A new `dict` that has all the entries of the given dictionaries.
34    """
35    result = {}
36    for d in dictionaries:
37        result.update(d)
38    result.update(kwargs)
39    return result
40
41def _omit(dictionary, keys):
42    """Returns a new `dict` that has all the entries of `dictionary` with keys not in `keys`.
43
44    Args:
45      dictionary: A `dict`.
46      keys: A sequence.
47
48    Returns:
49      A new `dict` that has all the entries of `dictionary` with keys not in `keys`.
50    """
51    keys_set = {k: None for k in keys}
52    return {k: dictionary[k] for k in dictionary if k not in keys_set}
53
54def _pick(dictionary, keys):
55    """Returns a new `dict` that has all the entries of `dictionary` with keys in `keys`.
56
57    Args:
58      dictionary: A `dict`.
59      keys: A sequence.
60
61    Returns:
62      A new `dict` that has all the entries of `dictionary` with keys in `keys`.
63    """
64    return {k: dictionary[k] for k in keys if k in dictionary}
65
66dicts = struct(
67    add = _add,
68    omit = _omit,
69    pick = _pick,
70)
71