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


Python AttrDict.items方法代码示例

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


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

示例1: test_iteration_2

# 需要导入模块: from attrdict import AttrDict [as 别名]
# 或者: from attrdict.AttrDict import items [as 别名]
    def test_iteration_2(self):
        """
        Test the iteration methods (items, keys, values[, iteritems,
        iterkeys, itervalues]).
        """
        if not PY2:  # Python2.6 doesn't have skipif/skipunless
            return

        from attrdict import AttrDict

        empty = AttrDict()
        adict = AttrDict({'foo': 'bar', 'lorem': 'ipsum', 'alpha': {
            'beta': 1, 'bravo': empty}})

        self.assertEqual(empty.items(), [])
        self.assertEqual(empty.keys(), [])
        self.assertEqual(empty.values(), [])

        items = adict.items()
        self.assertEqual(len(items), 3)
        self.assertTrue(('foo', 'bar') in items)
        self.assertTrue(('lorem', 'ipsum') in items)
        self.assertTrue(('alpha', {'beta': 1, 'bravo': empty}) in items)

        self.assertEqual(set(adict.keys()), set(['foo', 'lorem', 'alpha']))

        values = adict.values()
        self.assertEqual(len(values), 3)
        self.assertTrue('bar' in values)
        self.assertTrue('ipsum' in values)
        self.assertTrue({'beta': 1, 'bravo': empty} in values)

        # Iterator methods
        iterator = empty.iteritems()
        self.assertFalse(isinstance(iterator, list))
        self.assertEqual(list(iterator), [])

        iterator = empty.iterkeys()
        self.assertFalse(isinstance(iterator, list))
        self.assertEqual(list(iterator), [])

        iterator = empty.itervalues()
        self.assertFalse(isinstance(iterator, list))
        self.assertEqual(list(iterator), [])

        iterator = adict.iteritems()
        self.assertFalse(isinstance(iterator, list))
        self.assertEqual(list(iterator), adict.items())

        iterator = adict.iterkeys()
        self.assertFalse(isinstance(iterator, list))
        self.assertEqual(list(iterator), adict.keys())

        iterator = adict.itervalues()
        self.assertFalse(isinstance(iterator, list))
        self.assertEqual(list(iterator), adict.values())
开发者ID:donsignore,项目名称:AttrDict,代码行数:58,代码来源:tests.py

示例2: Process

# 需要导入模块: from attrdict import AttrDict [as 别名]
# 或者: from attrdict.AttrDict import items [as 别名]
class Process(object):
    """A generic parent class for all climlab process objects.
    Every process object has a set of state variables on a spatial grid.

    For more general information about `Processes` and their role in climlab,
    see :ref:`process_architecture` section climlab-architecture.

    **Initialization parameters** \n

    An instance of ``Process`` is initialized with the following
    arguments *(for detailed information see Object attributes below)*:

    :param Field state: spatial state variable for the process.
                        Set to ``None`` if not specified.
    :param domains:     domain(s) for the process
    :type domains:      :class:`~climlab.domain.domain._Domain` or dict of
                        :class:`~climlab.domain.domain._Domain`
    :param subprocess:  subprocess(es) of the process
    :type subprocess:   :class:`~climlab.process.process.Process` or dict of
                        :class:`~climlab.process.process.Process`
    :param array lat:   latitudinal points (optional)
    :param lev:         altitudinal points (optional)
    :param int num_lat: number of latitudional points (optional)
    :param int num_levels:
                        number of altitudinal points (optional)
    :param dict input:  collection of input quantities
    :param bool verbose: Flag to control text output during instantiation
                         of the Process [default: True]

    **Object attributes** \n

    Additional to the parent class :class:`~climlab.process.process.Process`
    following object attributes are generated during initialization:

    :ivar dict domains:     dictionary of process :class:`~climlab.domain.domain._Domain`
    :ivar dict state:       dictionary of process states
                            (of type :class:`~climlab.domain.field.Field`)
    :ivar dict param:       dictionary of model parameters which are given
                            through ``**kwargs``
    :ivar dict diagnostics: a dictionary with all diagnostic variables
    :ivar dict _input_vars: collection of input quantities like boundary conditions
                            and other gridded quantities
    :ivar str creation_date:
                            date and time when process was created
    :ivar subprocess:       dictionary of suprocesses of the process
    :vartype subprocess:    dict of :class:`~climlab.process.process.Process`

    """

    def __str__(self):
        str1 = 'climlab Process of type {0}. \n'.format(type(self))
        str1 += 'State variables and domain shapes: \n'
        for varname in list(self.state.keys()):
            str1 += '  {0}: {1} \n'.format(varname, self.domains[varname].shape)
        str1 += 'The subprocess tree: \n'
        str1 += walk.process_tree(self, name=self.name)
        return str1

    def __init__(self, name='Untitled', state=None, domains=None, subprocess=None,
                 lat=None, lev=None, num_lat=None, num_levels=None,
                 input=None, verbose=True, **kwargs):
        # verbose flag used to control text output at process creation time
        self.verbose = verbose
        self.name = name
        # dictionary of domains. Keys are the domain names
        self.domains = _make_dict(domains, _Domain)
        #  If lat is given, create a simple domains
        if lat is not None:
            sfc = zonal_mean_surface()
            self.domains.update({'default': sfc})
        # dictionary of state variables (all of type Field)
        self.state = AttrDict()
        states = _make_dict(state, Field)
        for name, value in states.items():
            self.set_state(name, value)
        # dictionary of model parameters
        self.param = kwargs
        # dictionary of diagnostic quantities
        #self.diagnostics = AttrDict()
        #self._diag_vars = frozenset()
        self._diag_vars = []
        # dictionary of input quantities
        #self.input = _make_dict(input, Field)
        if input is None:
            #self._input_vars = frozenset()
            self._input_vars = []
        else:
            self.add_input(list(input.keys()))
            for name, var in input:
                self.__dict__[name] = var
        self.creation_date = time.strftime("%a, %d %b %Y %H:%M:%S %z",
                                           time.localtime())
        # subprocess is a dictionary of any sub-processes
        self.subprocess = AttrDict()
        if subprocess is not None:
            self.add_subprocesses(subprocess)
        #if subprocess is None:
        #    #self.subprocess = {}
        #    # a dictionary whose items can be accessed as attributes
        #    self.subprocess = AttrDict()
#.........这里部分代码省略.........
开发者ID:brian-rose,项目名称:climlab,代码行数:103,代码来源:process.py

示例3: Widget

# 需要导入模块: from attrdict import AttrDict [as 别名]
# 或者: from attrdict.AttrDict import items [as 别名]

#.........这里部分代码省略.........
      self.set_value(name, val)
        
  def _normalize_id(self, id):
    """ Removes illegal characters from the widget id. The id can appear in HTML, 
    as file name, as part of css. """
    return re.sub('[^a-zA-Z_0-9]', '_', id)
    #return id.replace(' ', '').replace('-','').replace('/','_').replace('\\', '_')

  def _get_widget(self, name):
    """ Gets a widget with the specified name. """
    name = self._normalize_id(name)
    if not name in self.widgets:
      raise Exception('name %s not found.' % name)
    return self.widgets[name]
      
  def _add_widget_if_needed(self, name, new_widget_type, *args, **kargs):
    name = self._normalize_id(name)
    if not name in self.widgets:
      return self._add_widget(name, new_widget_type, *args, **kargs)
    return self.widgets[name]
    
  def _add_widget(self, name, new_widget_type, *args, **kargs):
    """ Adds a sub widget. """
    name = self._normalize_id(name)
    if name in self.widgets:
      raise Exception('name %s is already in use' % name)
    new_id = '%s%s%s' % (self.id, ID_SEPERATOR, name)
    new_widget = new_widget_type(new_id, self, *args, **kargs)   
    self.widgets[name] = new_widget
    return new_widget
  
  def _remove_widget(self, widget):
    """ Removes a sub widget. """
    widget_name = widget.id.split(ID_SEPERATOR)[-1]
    del self.widgets[widget_name]
  
  def run_on_load(self):
    """ Called by a Report when a widget is reloaded. """
    for w in self.widgets.values():
      w.run_on_load()
    if 'on_load' in dir(self):
      self.on_load()
  
  def _get_unique_id(self):
    """ Returns a unique id. Multiple calls to this function 
    will no generate the same id.
    """
    if not self.unique_counter:
      ret = self.id
    else:
      ret = '%s_%d' % (self.id, self.unique_counter)
    self.unique_counter += 1
    return ret

  def _save_value_if_needed(self, value_name, value):
    """ This function saves the given value according to the last
    key used in _guess_or_remember.
    """
    if not value_name in self.value_name_to_cache_key:
      return
    cache_key = self.value_name_to_cache_key[value_name]
    dict_name = str(type(self))
    cache_dict = CACHE.get(dict_name, none_if_not_found=True)
    if not cache_dict:
      cache_dict = {}
    cache_dict[cache_key] = value
    CACHE.put(dict_name, cache_dict, dict_name)

  def _guess_or_remember(self, value_name, key, default_value=None):
    """ Used to suggest a default for a certain value of the widget, or
    record the selected value. 
    If there is no value in values.choices:
      The method will look for a value under 'key', and set values.[value_name]
      to that value. If there is no value, values.[value_name] is set to default_value.
    If there is a value in values.choices:
      The value is saved under 'key'.
      
    Any subsequent changes to value_name are saved under 'key'.
    """
    key = make_unique_str(key)
    dict_name = str(type(self))
    cache_dict = CACHE.get(dict_name, none_if_not_found=True)
    if not cache_dict:
      cache_dict = {}
    if self.values[value_name] == None:
      self.values[value_name] = cache_dict.get(key, default_value)
    else:
      cache_dict[key] = self.values[value_name]
      CACHE.put(dict_name, cache_dict, dict_name)
    # make sure we will update the value in cache when it changes:
    self.value_name_to_cache_key[value_name] = key

  def __str__(self):
    my_str = '%s' % '{%s}' % ','.join(['%s: %s' % (k,v) for k,v in self.values.items()])
    sub_widgets = '\n'.join('%s - %s' % (k,str(v)) for k,v in self.widgets.items())
    if sub_widgets:
      sub_widgets = '\n'.join(['  %s' % s for s in sub_widgets.split('\n')])
      return '%s\n%s' % (my_str, sub_widgets)
    else:
      return my_str
开发者ID:ericjsolis,项目名称:danapeerlab,代码行数:104,代码来源:widget.py


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