本文整理汇总了Python中cyordereddict.OrderedDict类的典型用法代码示例。如果您正苦于以下问题:Python OrderedDict类的具体用法?Python OrderedDict怎么用?Python OrderedDict使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了OrderedDict类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_copying
def test_copying(self):
# Check that ordered dicts are copyable, deepcopyable, picklable,
# and have a repr/eval round-trip
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs)
update_test = OrderedDict()
update_test.update(od)
for label, dup in [
('od.copy()', od.copy()),
('copy.copy(od)', copy.copy(od)),
('copy.deepcopy(od)', copy.deepcopy(od)),
('pickle.loads(pickle.dumps(od, 0))',
pickle.loads(pickle.dumps(od, 0))),
('pickle.loads(pickle.dumps(od, 1))',
pickle.loads(pickle.dumps(od, 1))),
('pickle.loads(pickle.dumps(od, 2))',
pickle.loads(pickle.dumps(od, 2))),
('pickle.loads(pickle.dumps(od, 3))',
pickle.loads(pickle.dumps(od, 3))),
('pickle.loads(pickle.dumps(od, -1))',
pickle.loads(pickle.dumps(od, -1))),
('eval(repr(od))', eval(repr(od))),
('update_test', update_test),
('OrderedDict(od)', OrderedDict(od)),
]:
with self.subTest(label=label):
msg = "\ncopy: %s\nod: %s" % (dup, od)
self.assertIsNot(dup, od, msg)
self.assertEqual(dup, od)
示例2: __setstate__
def __setstate__(self, state):
OLDEST_SUPPORTED_STATE = 1
version = state.pop(VERSION_LABEL)
if version < OLDEST_SUPPORTED_STATE:
raise BaseException("PerformancePeriod saved state is too old.")
processed_transactions = defaultdict(list)
processed_transactions.update(state.pop('processed_transactions'))
orders_by_id = OrderedDict()
orders_by_id.update(state.pop('orders_by_id'))
orders_by_modified = defaultdict(OrderedDict)
orders_by_modified.update(state.pop('orders_by_modified'))
positions = positiondict()
positions.update(state.pop('positions'))
_positions_store = zp.Positions()
_positions_store.update(state.pop('_positions_store'))
self.processed_transactions = processed_transactions
self.orders_by_id = orders_by_id
self.orders_by_modified = orders_by_modified
self.positions = positions
self._positions_store = _positions_store
self.__dict__.update(state)
self.initialize_position_calc_arrays()
示例3: __setstate__
def __setstate__(self, state):
OLDEST_SUPPORTED_STATE = 1
version = state.pop(VERSION_LABEL)
if version < OLDEST_SUPPORTED_STATE:
raise BaseException("PerformancePeriod saved state is too old.")
processed_transactions = {}
processed_transactions.update(state.pop('processed_transactions'))
orders_by_id = OrderedDict()
orders_by_id.update(state.pop('orders_by_id'))
orders_by_modified = {}
orders_by_modified.update(state.pop('orders_by_modified'))
self.processed_transactions = processed_transactions
self.orders_by_id = orders_by_id
self.orders_by_modified = orders_by_modified
# pop positions to use for v1
positions = state.pop('positions', None)
self.__dict__.update(state)
if version == 1:
# version 1 had PositionTracker logic inside of Period
# we create the PositionTracker here.
# Note: that in V2 it is assumed that the position_tracker
# will be dependency injected and so is not reconstructed
assert positions is not None, "positions should exist in v1"
position_tracker = PositionTracker()
position_tracker.update_positions(positions)
self.position_tracker = position_tracker
示例4: test_clear
def test_clear(self):
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
self.assertEqual(len(od), len(pairs))
od.clear()
self.assertEqual(len(od), 0)
示例5: test_delitem
def test_delitem(self):
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs)
del od['a']
self.assertNotIn('a', od)
with self.assertRaises(KeyError):
del od['a']
self.assertEqual(list(od.items()), pairs[:2] + pairs[3:])
示例6: _stats
def _stats(self):
_stats = OrderedDict()
_stats['id_string'] = self._get_id_string()
_stats['version'] = self.id
_stats['row_count'] = len(self.schema.get('content', {}).get('survey', []))
# returns stats in the format [ key="value" ]
return '\n\t'.join(map(lambda key: '%s="%s"' % (key, str(_stats[key])),
_stats.keys()))
示例7: test_yaml_linkage
def test_yaml_linkage(self):
# Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature.
# In yaml, lists are native but tuples are not.
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs)
# yaml.dump(od) -->
# '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n'
self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1]))
示例8: test_popitem
def test_popitem(self):
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
while pairs:
self.assertEqual(od.popitem(), pairs.pop())
with self.assertRaises(KeyError):
od.popitem()
self.assertEqual(len(od), 0)
示例9: test_reinsert
def test_reinsert(self):
# Given insert a, insert b, delete a, re-insert a,
# verify that a is now later than b.
od = OrderedDict()
od['a'] = 1
od['b'] = 2
del od['a']
od['a'] = 1
self.assertEqual(list(od.items()), [('b', 2), ('a', 1)])
示例10: _stats
def _stats(self):
_stats = OrderedDict()
_stats['id_string'] = self.id_string
_stats['versions'] = len(self.versions)
# _stats['submissions'] = self.submissions_count()
_stats['row_count'] = len(self[-1].schema.get('content', {})
.get('survey', []))
# returns stats in the format [ key="value" ]
return '\n\t'.join('%s="%s"' % item for item in _stats.items())
示例11: __init__
def __init__(self):
# sid => position object
self.positions = positiondict()
# Arrays for quick calculations of positions value
self._position_amounts = OrderedDict()
self._position_last_sale_prices = OrderedDict()
self._unpaid_dividends = pd.DataFrame(
columns=zp.DIVIDEND_PAYMENT_FIELDS,
)
self._positions_store = zp.Positions()
示例12: test_iterators
def test_iterators(self):
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
self.assertEqual(list(od), [t[0] for t in pairs])
self.assertEqual(list(od.keys()), [t[0] for t in pairs])
self.assertEqual(list(od.values()), [t[1] for t in pairs])
self.assertEqual(list(od.items()), pairs)
self.assertEqual(list(reversed(od)),
[t[0] for t in reversed(pairs)])
示例13: writegrammar
def writegrammar(grammar, bitpar=False):
"""Write a grammar in a simple text file format.
Rules are written in the order as they appear in the sequence `grammar`,
except that the lexicon file lists words in sorted order (with tags for
each word in the order of `grammar`). For a description of the file format,
see ``docs/fileformats.rst``.
:param grammar: a sequence of rule tuples, as produced by
``treebankgrammar()``, ``dopreduction()``, or ``doubledop()``.
:param bitpar: when ``True``, use bitpar format: for rules, put weight
first and leave out the yield function. By default, a format that
supports LCFRS is used.
:returns: tuple of strings``(rules, lexicon)``
Weights are written in the following format:
- if ``bitpar`` is ``False``, write rational fractions; e.g., ``2/3``.
- if ``bitpar`` is ``True``, write frequencies (e.g., ``2``)
if probabilities sum to 1, i.e., in that case probabilities can be
re-computed as relative frequencies. Otherwise, resort to floating
point numbers (e.g., ``0.666``, imprecise)."""
rules, lexicon = [], []
lexical = OrderedDict()
freqs = bitpar
for (r, yf), w in grammar:
if isinstance(w, tuple):
if freqs:
w = '%g' % w[0]
else:
w1, w2 = w
if bitpar:
w = '%s' % (w1 / w2) # .hex()
else:
w = '%s/%s' % (w1, w2)
elif isinstance(w, float):
w = w.hex()
if len(r) == 2 and r[1] == 'Epsilon':
lexical.setdefault(yf[0], []).append((r[0], w))
continue
elif bitpar:
rules.append(('%s\t%s\n' % (w, '\t'.join(x for x in r))))
else:
yfstr = ','.join(''.join(map(str, a)) for a in yf)
rules.append(('%s\t%s\t%s\n' % (
'\t'.join(x for x in r), yfstr, w)))
for word in lexical:
lexicon.append(unescape(word))
for tag, w in lexical[word]:
lexicon.append('\t%s %s' % (tag, w))
lexicon.append('\n')
return ''.join(rules), ''.join(lexicon)
示例14: __init__
def __init__(self, versions=None, title='Submissions', id_string=None,
default_version_id_key='__version__',
strict_schema=False,
root_node_name='data',
asset_type=None, submissions_xml=None):
if not versions:
versions = []
# accept a single version, but normalize it to an iterable
if isinstance(versions, dict):
versions = [versions]
self.versions = OrderedDict()
# the name of the field in submissions which stores the version ID
self.default_version_id_key = default_version_id_key
self.id_string = id_string
self.root_node_name = root_node_name
self.title = title
self.strict_schema = strict_schema
if len(self.title) > 31: # excel sheet name size limit
self.title = self.title[:28] + '...'
self.asset_type = asset_type
self.load_all_versions(versions)
示例15: __setstate__
def __setstate__(self, state):
OLDEST_SUPPORTED_STATE = 3
version = state.pop(VERSION_LABEL)
if version < OLDEST_SUPPORTED_STATE:
raise BaseException("PositionTracker saved state is too old.")
self.asset_finder = state['asset_finder']
self.positions = positiondict()
# note that positions_store is temporary and gets regened from
# .positions
self._positions_store = zp.Positions()
self._unpaid_dividends = state['unpaid_dividends']
self._auto_close_position_sids = state['auto_close_position_sids']
# Arrays for quick calculations of positions value
self._position_amounts = OrderedDict()
self._position_last_sale_prices = OrderedDict()
self._position_value_multipliers = OrderedDict()
self._position_exposure_multipliers = OrderedDict()
self._position_payout_multipliers = OrderedDict()
# Update positions is called without a finder
self.update_positions(state['positions'])