def items(self, *args, **kwargs):
return PresortedList(OrderedDict.items(self, *args, **kwargs))
python类items()的实例源码
def validate_properties(self, node, key, properties):
if properties is None:
return self.error('properties value must be a map, not null', key)
for property_name, property in properties.iteritems():
if hasattr(property, 'keys'):
p_type = property.get('type')
if p_type == 'array':
if not 'items' in property:
self.error('items must be present if the type is array: %s' % property, property_name)
else:
if 'items' in property:
self.error('items must be only be present if the type is array: %s' % property, property_name)
else:
self.error('property must be a map: %s' % property, property_name)
self.check_and_validate_keywords(self.__class__.property_keywords, property, property_name)
def validate_property_items(self, node, key, items):
self.check_and_validate_keywords(self.__class__.property_keywords, items, key)
def marked_load(self, stream):
def construct_mapping(loader, node):
keys = [node_tuple[0].value for node_tuple in node.value]
for item, count in Counter(keys).items():
if count > 1:
key_nodes = [node_tuple[0] for node_tuple in node.value if node_tuple[0].value == item]
self.warning('%s occurs %s times, at %s' % (item, count, ' and '.join(['line %s, column %s' % (key_node.start_mark.line + 1, key_node.start_mark.column + 1) for key_node in key_nodes])))
loader.flatten_mapping(node)
return PresortedOrderedDict(loader.construct_pairs(node))
MarkedLoader.add_constructor(
Resolver.DEFAULT_MAPPING_TAG,
construct_mapping)
return MarkedLoader(stream).get_single_data()
def items(self, *args, **kwargs):
return _UnsortableList(OrderedDict.items(self, *args, **kwargs))
def merge(self, other):
"""
Gather operations from other and merge them into my operations.
"""
for key, value in sorted(other._operations.items()):
self.addOperation(key, value)
def representCleanOpenAPIOperation(dumper, data):
"""
Unpack nonstandard attributes while representing an OpenAPIOperation
"""
dct = _orderedCleanDict(data)
if '_extended' in dct:
for k, ext in data._extended.items():
dct[k] = ext
del dct['_extended']
return dumper.represent_dict(dct)
def representCleanOpenAPIPathItem(dumper, data):
"""
Unpack operation key/values before representing an OpenAPIPathItem
"""
dct = _orderedCleanDict(data)
if '_operations' in dct:
items = sorted(data._operations.items())
for k, op in items:
dct[k] = op
del dct['_operations']
return dumper.represent_dict(dct)
def __init__(self, init_val=(), strict=False):
"""
Create a new ordered dictionary. Cannot init from a normal dict,
nor from kwargs, since items order is undefined in those cases.
If the ``strict`` keyword argument is ``True`` (``False`` is the
default) then when doing slice assignment - the ``OrderedDict`` you are
assigning from *must not* contain any keys in the remaining dict.
>>> OrderedDict()
OrderedDict([])
>>> OrderedDict({1: 1})
Traceback (most recent call last):
TypeError: undefined order, cannot get items from dict
>>> OrderedDict({1: 1}.items())
OrderedDict([(1, 1)])
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d
OrderedDict([(1, 3), (3, 2), (2, 1)])
>>> OrderedDict(d)
OrderedDict([(1, 3), (3, 2), (2, 1)])
"""
self.strict = strict
dict.__init__(self)
if isinstance(init_val, OrderedDict):
self._sequence = init_val.keys()
dict.update(self, init_val)
elif isinstance(init_val, dict):
# we lose compatibility with other ordered dict types this way
raise TypeError('undefined order, cannot get items from dict')
else:
self._sequence = []
self.update(init_val)
### Special methods ###
def items(self):
"""
``items`` returns a list of tuples representing all the
``(key, value)`` pairs in the dictionary.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.items()
[(1, 3), (3, 2), (2, 1)]
>>> d.clear()
>>> d.items()
[]
"""
return zip(self._sequence, self.values())
def update(self, from_od):
"""
Update from another OrderedDict or sequence of (key, value) pairs
>>> d = OrderedDict(((1, 0), (0, 1)))
>>> d.update(OrderedDict(((1, 3), (3, 2), (2, 1))))
>>> d
OrderedDict([(1, 3), (0, 1), (3, 2), (2, 1)])
>>> d.update({4: 4})
Traceback (most recent call last):
TypeError: undefined order, cannot get items from dict
>>> d.update((4, 4))
Traceback (most recent call last):
TypeError: cannot convert dictionary update sequence element "4" to a 2-item sequence
"""
if isinstance(from_od, OrderedDict):
for key, val in from_od.items():
self[key] = val
elif isinstance(from_od, dict):
# we lose compatibility with other ordered dict types this way
raise TypeError('undefined order, cannot get items from dict')
else:
# FIXME: efficiency?
# sequence of 2-item sequences, or error
for item in from_od:
try:
key, val = item
except TypeError:
raise TypeError('cannot convert dictionary update'
' sequence element "%s" to a 2-item sequence' % item)
self[key] = val
def rename(self, old_key, new_key):
"""
Rename the key for a given value, without modifying sequence order.
For the case where new_key already exists this raise an exception,
since if new_key exists, it is ambiguous as to what happens to the
associated values, and the position of new_key in the sequence.
>>> od = OrderedDict()
>>> od['a'] = 1
>>> od['b'] = 2
>>> od.items()
[('a', 1), ('b', 2)]
>>> od.rename('b', 'c')
>>> od.items()
[('a', 1), ('c', 2)]
>>> od.rename('c', 'a')
Traceback (most recent call last):
ValueError: New key already exists: 'a'
>>> od.rename('d', 'b')
Traceback (most recent call last):
KeyError: 'd'
"""
if new_key == old_key:
# no-op
return
if new_key in self:
raise ValueError("New key already exists: %r" % new_key)
# rename sequence entry
value = self[old_key]
old_idx = self._sequence.index(old_key)
self._sequence[old_idx] = new_key
# rename internal dict entry
dict.__delitem__(self, old_key)
dict.__setitem__(self, new_key, value)
def __delitem__(self, i): raise TypeError('Can\'t delete items from keys')
def append(self, item): raise TypeError('Can\'t append items to keys')
def insert(self, i, item): raise TypeError('Can\'t insert items into keys')
def pop(self, i=-1): raise TypeError('Can\'t pop items from keys')
def remove(self, item): raise TypeError('Can\'t remove items from keys')
def __getitem__(self, index):
"""Fetch the item at position i."""
if isinstance(index, types.SliceType):
# fetching a slice returns an OrderedDict
return self._main[index].items()
key = self._main._sequence[index]
return (key, self._main[key])
def __repr__(self): return repr(self._main.items())
# FIXME: do we need to check if we are comparing with another ``Items``
# object? (like the __cast method of UserList)
def __lt__(self, other): return self._main.items() < other