當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。