当前位置: 首页>>代码示例>>Python>>正文


Python collections.Mapping方法代码示例

本文整理汇总了Python中collections.Mapping方法的典型用法代码示例。如果您正苦于以下问题:Python collections.Mapping方法的具体用法?Python collections.Mapping怎么用?Python collections.Mapping使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在collections的用法示例。


在下文中一共展示了collections.Mapping方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: floatify_latlng

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def floatify_latlng(input_value):
    """
    Work around a JSON dict with string, not float, lat/lngs.

    Given anything (list/dict/etc) it will return that thing again, *but* any
    dict (at any level) that has only 2 elements lat & lng, will be replaced
    with the lat & lng turned into floats.

    If the API returns the lat/lng as strings, and not numbers, then this
    function will 'clean them up' to be floats.
    """
    if isinstance(input_value, collections.Mapping):
        if len(input_value) == 2 and sorted(input_value.keys()) == ['lat', 'lng']:
            # This dict has only 2 keys 'lat' & 'lon'
            return {'lat': float_if_float(input_value["lat"]), 'lng': float_if_float(input_value["lng"])}
        else:
            return dict((key, floatify_latlng(value)) for key, value in input_value.items())
    elif isinstance(input_value, collections.MutableSequence):
        return [floatify_latlng(x) for x in input_value]
    else:
        return input_value 
开发者ID:OpenCageData,项目名称:python-opencage-geocoder,代码行数:23,代码来源:geocoder.py

示例2: normalize_nested_keys

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def normalize_nested_keys(config):
    """ Replaces underscores with hyphens for keys for a nested Mapping

    Examples
    --------
    >>> a = {'x': 1, 'y_1': {'a_2': 2}}
    >>> normalize_nested_keys(a)
    {'x': 1, 'y-1': {'a-2': 2}}
    """
    config_norm = {}
    for key, value in config.items():
        if isinstance(value, Mapping):
            value = normalize_nested_keys(value)
        key_norm = normalize_key(key)
        config_norm[key_norm] = value

    return config_norm 
开发者ID:NCAR,项目名称:esmlab,代码行数:19,代码来源:config.py

示例3: extend

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def extend(self, *args, **kwargs):
        """Generic import function for any type of header-like object.
        Adapted version of MutableMapping.update in order to insert items
        with self.add instead of self.__setitem__
        """
        if len(args) > 1:
            raise TypeError("extend() takes at most 1 positional "
                            "arguments ({} given)".format(len(args)))
        other = args[0] if len(args) >= 1 else ()
        
        if isinstance(other, HTTPHeaderDict):
            for key, val in other.iteritems():
                self.add(key, val)
        elif isinstance(other, Mapping):
            for key in other:
                self.add(key, other[key])
        elif hasattr(other, "keys"):
            for key in other.keys():
                self.add(key, other[key])
        else:
            for key, value in other:
                self.add(key, value)

        for key, value in kwargs.items():
            self.add(key, value) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:27,代码来源:_collections.py

示例4: update

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def update(d, u, depth=-1):
    """
    Recursively merge or update dict-like objects.
    >>> update({'k1': {'k2': 2}}, {'k1': {'k2': {'k3': 3}}, 'k4': 4})
    {'k1': {'k2': {'k3': 3}}, 'k4': 4}
    """

    for k, v in u.iteritems():
        if isinstance(v, Mapping) and not depth == 0:
            r = update(d.get(k, {}), v, depth=max(depth - 1, -1))
            d[k] = r
        elif isinstance(d, Mapping):
            d[k] = u[k]
        else:
            d = {k: u[k]}
    return d 
开发者ID:dulacp,项目名称:django-accounting,代码行数:18,代码来源:foundation.py

示例5: extend

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def extend(self, *args, **kwargs):
        """Generic import function for any type of header-like object.
        Adapted version of MutableMapping.update in order to insert items
        with self.add instead of self.__setitem__
        """
        if len(args) > 1:
            raise TypeError("extend() takes at most 1 positional "
                            "arguments ({0} given)".format(len(args)))
        other = args[0] if len(args) >= 1 else ()

        if isinstance(other, HTTPHeaderDict):
            for key, val in other.iteritems():
                self.add(key, val)
        elif isinstance(other, Mapping):
            for key in other:
                self.add(key, other[key])
        elif hasattr(other, "keys"):
            for key in other.keys():
                self.add(key, other[key])
        else:
            for key, value in other:
                self.add(key, value)

        for key, value in kwargs.items():
            self.add(key, value) 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:27,代码来源:_collections.py

示例6: encode

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def encode(self, payload, key, algorithm='HS256', headers=None,
               json_encoder=None):
        # Check that we get a mapping
        if not isinstance(payload, Mapping):
            raise TypeError('Expecting a mapping object, as JWT only supports '
                            'JSON objects as payloads.')

        # Payload
        for time_claim in ['exp', 'iat', 'nbf']:
            # Convert datetime to a intDate value in known time-format claims
            if isinstance(payload.get(time_claim), datetime):
                payload[time_claim] = timegm(payload[time_claim].utctimetuple())

        json_payload = json.dumps(
            payload,
            separators=(',', ':'),
            cls=json_encoder
        ).encode('utf-8')

        return super(PyJWT, self).encode(
            json_payload, key, algorithm, headers, json_encoder
        ) 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:24,代码来源:api_jwt.py

示例7: _update_nested_dictionary

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def _update_nested_dictionary(dict_, other):
    """Update a nested dictionary with another dictionary.

    The basic ``.update()`` method of dictionaries adds non-existing keys or replaces
    existing keys which works fine for unnested dictionaries. For nested dictionaries,
    levels under the current level are not updated but overwritten. This function
    recursively loops over keys and values and inserts the value if it is not a
    dictionary. If it is a dictionary, it applies the same process again.

    """
    for key, value in other.items():
        if isinstance(value, collections.Mapping):
            dict_[key] = _update_nested_dictionary(dict_.get(key, {}), value)
        else:
            dict_[key] = value
    return dict_ 
开发者ID:OpenSourceEconomics,项目名称:respy,代码行数:18,代码来源:random_model.py

示例8: execfile

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def execfile(filename, myglobals=None, mylocals=None):
        """
        Read and execute a Python script from a file in the given namespaces.
        The globals and locals are dictionaries, defaulting to the current
        globals and locals. If only globals is given, locals defaults to it.
        """
        if myglobals is None:
            # There seems to be no alternative to frame hacking here.
            caller_frame = inspect.stack()[1]
            myglobals = caller_frame[0].f_globals
            mylocals = caller_frame[0].f_locals
        elif mylocals is None:
            # Only if myglobals is given do we set mylocals to it.
            mylocals = myglobals
        if not isinstance(myglobals, Mapping):
            raise TypeError('globals must be a mapping')
        if not isinstance(mylocals, Mapping):
            raise TypeError('locals must be a mapping')
        with open(filename, "rbU") as fin:
             source = fin.read()
        code = compile(source, filename, "exec")
        exec_(code, myglobals, mylocals) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:24,代码来源:misc.py

示例9: thaw

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def thaw(obj):
  """Takes a a frozen object, and returns a mutable version of it.

  Conversions:
    * collections.Mapping -> dict
    * tuple -> list
    * frozenset -> set

  Close to the opposite of freeze().
  Does not convert dict keys.
  """
  if isinstance(obj, (dict, collections.OrderedDict, FrozenDict)):
    return {k: thaw(v) for k, v in obj.iteritems()}
  elif isinstance(obj, (list, tuple)):
    return [thaw(i) for i in obj]
  elif isinstance(obj, (set, frozenset)):
    return {thaw(i) for i in obj}
  else:
    return obj 
开发者ID:luci,项目名称:recipes-py,代码行数:21,代码来源:types.py

示例10: dict_update

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def dict_update(d, u):
    """Improved update for nested dictionaries.

    Arguments:
        d: The dictionary to be updated.
        u: The update dictionary.

    Returns:
        The updated dictionary.
    """
    d = d.copy()
    for k, v in u.items():
        if isinstance(v, collections.Mapping):
            d[k] = dict_update(d.get(k, {}), v)
        else:
            d[k] = v
    return d 
开发者ID:ethz-asl,项目名称:hierarchical_loc,代码行数:19,代码来源:tools.py

示例11: repr_dict

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def repr_dict(_dict, indent):
    """Return a debug representation of a dict or OrderedDict."""
    # pprint represents OrderedDict objects using the tuple init syntax,
    # which is not very readable. Therefore, dictionaries are iterated over.
    if _dict is None:
        return 'None'
    if not isinstance(_dict, Mapping):
        raise TypeError("Object must be a mapping, but is a %s" %
                        type(_dict))
    if isinstance(_dict, OrderedDict):
        kind = 'ordered'
        ret = '%s {\n' % kind  # non standard syntax for the kind indicator
        for key in six.iterkeys(_dict):
            value = _dict[key]
            ret += _indent('%r: %r,\n' % (key, value), 2)
    else:  # dict
        kind = 'sorted'
        ret = '%s {\n' % kind  # non standard syntax for the kind indicator
        for key in sorted(six.iterkeys(_dict)):
            value = _dict[key]
            ret += _indent('%r: %r,\n' % (key, value), 2)
    ret += '}'
    ret = repr_text(ret, indent=indent)
    return ret.lstrip(' ') 
开发者ID:zhmcclient,项目名称:python-zhmcclient,代码行数:26,代码来源:_utils.py

示例12: configure

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def configure(args):
    for group, policies in config.managed_iam_groups.items():
        print("Creating group", group)
        formatted_policies = [(IAMPolicyBuilder(**p) if isinstance(p, collections.Mapping) else p) for p in policies]
        ensure_iam_group(group, policies=formatted_policies)
        msg = 'Created group {g}. Use the AWS console or "aws iam add-user-to-group --user-name USER --group-name {g}" to add users to it.' # noqa
        print(BOLD(msg.format(g=group))) 
开发者ID:kislyuk,项目名称:aegea,代码行数:9,代码来源:iam.py

示例13: namedtuple_with_defaults

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def namedtuple_with_defaults(typename, field_names, default_values=()):
    """ create a namedtuple with default values """
    T = collections.namedtuple(typename, field_names)
    T.__new__.__defaults__ = (None, ) * len(T._fields)
    if isinstance(default_values, collections.Mapping):
        prototype = T(**default_values)
    else:
        prototype = T(*default_values)
    T.__new__.__defaults__ = tuple(prototype)
    return T 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:12,代码来源:utils.py

示例14: update

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def update(old, new, priority='new'):
    """ Update a nested dictionary with values from another
    This is like dict.update except that it smoothly merges nested values
    This operates in-place and modifies old
    Parameters
    ----------
    priority: string {'old', 'new'}
        If new (default) then the new dictionary has preference.
        Otherwise the old dictionary does.

    """

    for k, v in new.items():
        if k not in old and isinstance(v, Mapping):
            old[k] = {}
        if isinstance(v, Mapping):
            if old[k] is None:
                old[k] = {}

            update(old[k], v, priority=priority)

        else:
            if priority == 'new' or k not in old:
                old[k] = v

    return old 
开发者ID:NCAR,项目名称:esmlab,代码行数:28,代码来源:config.py

示例15: expand_environment_variables

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Mapping [as 别名]
def expand_environment_variables(config):
    ''' Expand environment variables in a nested config dictionary

    This function will recursively search through any nested dictionaries
    and/or lists.

    Parameters
    ----------
    config : dict, iterable, or str
        Input object to search for environment variables

    Returns
    -------
    config : same type as input

    Examples
    --------
    >>> expand_environment_variables({'x': [1, 2, '$USER']})  # doctest: +SKIP
    {'x': [1, 2, 'my-username']}
    '''
    if isinstance(config, Mapping):
        return {k: expand_environment_variables(v) for k, v in config.items()}
    elif isinstance(config, str):
        return os.path.expanduser(os.path.expandvars(config))
    elif isinstance(config, (list, tuple, set)):
        return type(config)([expand_environment_variables(v) for v in config])
    else:
        return config 
开发者ID:NCAR,项目名称:esmlab,代码行数:30,代码来源:config.py


注:本文中的collections.Mapping方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。