本文整理汇总了Python中odict.OrderedDict.items方法的典型用法代码示例。如果您正苦于以下问题:Python OrderedDict.items方法的具体用法?Python OrderedDict.items怎么用?Python OrderedDict.items使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类odict.OrderedDict
的用法示例。
在下文中一共展示了OrderedDict.items方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Node
# 需要导入模块: from odict import OrderedDict [as 别名]
# 或者: from odict.OrderedDict import items [as 别名]
class Node(object):
def __init__(self, name):
self.name = name
self.attributes = OrderedDict()
self.children = []
self.parent = None
def __eq__(self, other):
return (type(other) == type(self) and
self.name == other.name and
dict(self.attributes) == dict(other.attributes) and
self.children == other.children)
def __ne__(self, other):
return not self == other
__gt__ = __lt__ = __ge__ = __le__ = not_implemented
__hash__ = None
def to_string(self):
attribute_string = "".join(' %s="%s"' % (key, value) for key, value in
self.attributes.items())
name = self.name
if not self.children:
return '<%s />' % (name + attribute_string)
children_string = "".join(node.to_string() for node in self.children)
return '<%s>%s</%s>' % (name + attribute_string, children_string, self.name)
# Hmmm...
__repr__ = to_string
示例2: sort_recursive
# 需要导入模块: from odict import OrderedDict [as 别名]
# 或者: from odict.OrderedDict import items [as 别名]
def sort_recursive(dictionary):
"""
Recursively sorts nested dictionaries. Should not be applied if the
structures are nested too deeply and/or there is even the remote
possibility that the nesting of the passed dictionary contains a cyclic
structure.
Args:
dictionary (dict): A python dictionary
Returns:
A recursively sorted dictionary
Example:
>>> dict = { 'a': '2', 'c': 3, 'b': { 'e': 4, 'd': 1 }, 'f': 5}
>>> sort_recursive(dict)
OrderedDict([('a', '2'), ('b', OrderedDict([('d', 1), ('e', 4)])), ('c', 3), ('f', 5)])
"""
sorted_list = OrderedDict(sorted(dictionary.items(), key = lambda x: x[0]))
# TODO test for cyclic structures.
for key, value in sorted_list.items():
if type(value) is dict:
sorted_list[key] = sort_recursive(value)
return sorted_list
示例3: startElement
# 需要导入模块: from odict import OrderedDict [as 别名]
# 或者: from odict.OrderedDict import items [as 别名]
def startElement(self, name, attrs):
self.path.append((name, attrs or None))
if len(self.path) > self.item_depth:
self.stack.append((self.item, self.data))
attrs = OrderedDict((self.attr_prefix+key, yaml_eval(value))
for (key, value) in attrs.items())
self.item = self.xml_attribs and attrs or None
self.data = None
示例4: merge_hists
# 需要导入模块: from odict import OrderedDict [as 别名]
# 或者: from odict.OrderedDict import items [as 别名]
def merge_hists(hists_d, merge_groups, order=PhysicsProcess.desired_plot_order):
"""
Merges the dictionary of input histograms according to the merge rules, which are specified
as a key-value dictionary, where the key is the target and value a list of (regular) expressions
to merge under the key.
For example, {
"WJets": ["W[1-4]Jets_.*"],
"tchan": ["T_t_ToLeptons", "Tbar_t_ToLeptons"],
} will perform the corresponding merges. The values of the merge dict are the keys of the input histogram dict.
returns - a dictionary with the merged histograms. Optionally you can specify a list with the desired order of the keys.
"""
for v in hists_d.values():
if not isinstance(v, Hist) and not isinstance(v, ROOT.TH1I) and not isinstance(v, ROOT.TH1F) and not isinstance(v, Hist2D) and not isinstance(v, ROOT.TH2I) and not isinstance(v, ROOT.TH2F):
raise ValueError("First argument(hists_d) must be a dict of Histograms, but found %s" % v)
out_d = OrderedDict()
logger.debug("merge_hists: input histograms %s" % str(hists_d))
for merge_name, items in merge_groups.items():
logger.debug("Merging %s to %s" % (items, merge_name))
matching_keys = []
for item in items:
t = filter(lambda x: re.match(item + "$", x), hists_d.keys())
matching_keys += t
logger.debug("Matched %s to %s" % (str(t), item))
if len(matching_keys)==0:
continue
logger.debug("Merging matched %s" % str(matching_keys))
hist = hists_d[matching_keys[0]].Clone()
for item in matching_keys[1:]:
hist.Add(hists_d[item])
out_d[merge_name] = hist
out_d[merge_name].SetTitle(merge_name)
out_d[merge_name].SetName(merge_name)
out_d_ordered = OrderedDict()
for elem in order:
try:
out_d_ordered[elem] = out_d.pop(elem)
if hasattr(PhysicsProcess, merge_name):
if type(getattr(PhysicsProcess, merge_name)) is dict: #take nominal name if multiple options
out_d_ordered[elem].SetTitle(getattr(PhysicsProcess, merge_name)["nominal"].pretty_name)
else: #regular
out_d_ordered[elem].SetTitle(getattr(PhysicsProcess, merge_name).pretty_name)
except KeyError: #We don't care if there was an element in the order which was not present in the merge output
pass
#Put anything that was not in the order list simply to the end
for k, v in out_d.items():
out_d_ordered[k] = v
return out_d_ordered
示例5: WidgetInChain
# 需要导入模块: from odict import OrderedDict [as 别名]
# 或者: from odict.OrderedDict import items [as 别名]
#.........这里部分代码省略.........
if idx == deleted_index:
choices_to_delete.append(input_choice)
if idx > deleted_index:
self.input_to_select[input].values.choices[i] = '%s,%s' % (idx - 1, out)
for choice in choices_to_delete:
self.input_to_select[input].values.choices.remove(choice)
def update_input_after_add(self, input, add_index):
for i, input_choice in enumerate(self.input_to_select[input].values.choices):
idx = int(input_choice.split(',')[0])
out = input_choice.split(',')[1]
if idx >= add_index:
self.input_to_select[input].values.choices[i] = '%s,%s' % (idx + 1, out)
def create_input_map(self, data):
input_map = {}
for input in self.input_to_select:
connected_outputs = self.get_idx_outputs(input)
connected_outputs = [data[idx][out] for idx,out in connected_outputs]
if connected_outputs:
input_map[input] = sum(connected_outputs[1:], connected_outputs[0])
else:
input_map[input] = None
return input_map
def run(self, data):
self.outputs_from_run = []
if self.widgets.sub_widget.has_method('run'):
if 'pre_run' in dir(self.widgets.sub_widget):
self.widgets.sub_widget.pre_run()
ret = self.widgets.sub_widget.run(**self.create_input_map(data))
#self.outputs_from_run = ret.keys()
return ret
def title(self, place_in_chain, short=False):
if self.widgets.sub_widget.has_method('title'):
ret = self.widgets.sub_widget.title(short)
else:
ret = widget_type_to_name(type(self.widgets.sub_widget))
if short:
return '[%d] %s' % (place_in_chain + 1, ret)
else:
return '%d. %s' % (place_in_chain + 1, ret)
def view(self, data, place_in_chain, possible_inputs):
def create_inputs_summary():
summary = []
for input in self.input_to_select:
choices = self.input_to_select[input].values.choices
choice_texts = [p[1] for p in possible_inputs if p[0] in choices]
#summary.append('%s: %s' % (input, choice_text))
summary.append('|'.join(choice_texts))
ret = ', '.join(summary)
if ret:
return 'Inputs: %s ' % ret
else:
if self.input_to_select:
return 'Inputs'
else:
return ''
#input_summary = View(self, '%sOutputs: %s' % (
# create_inputs_summary(),
# ', '.join(self.get_outputs())))
input_summary = View(self, create_inputs_summary())
input_content_views = []
for k,v in self.input_to_select.items():
input_content_views.append(v.view(
k, self.widgets.input_apply, possible_inputs, multiple=True))
input_content_views.append(self.widgets.input_apply.view())
input_content = view.stack_lines(*input_content_views)
try:
sub_widget_view = self.widgets.sub_widget.view(**self.create_input_map(data))
except Exception as e:
logging.exception('Exception in view')
sub_widget_view = View(self, str(e))
global CHAINABLE_WIDGETS
widget_control_view = stack_left(
self.widgets.new_widget_select.view('', self.widgets.apply_new_widget, zip(*CHAINABLE_WIDGETS)[0], False),
self.widgets.apply_new_widget.view('Add before'),
self.widgets.delete_button.view('Delete'))
widget_control_view.main_html = '<div style="position:absolute; top:0; right:0;">%s</div>' % widget_control_view.main_html
sub_view = view.stack_lines(
widget_control_view,
self.widgets.input_panel.view(input_summary, input_content),
view.vertical_seperator(),
sub_widget_view)
#sub_view = self.widgets.sub_widget.view(data)
#title_view = view.left_right(
# View(self, self.title(place_in_chain)),
# self.widgets.delete_button.view('Delete'))
title_view = View(self, self.title(place_in_chain))
return self.widgets.expander.view(title_view, sub_view)
示例6: Dialog
# 需要导入模块: from odict import OrderedDict [as 别名]
# 或者: from odict.OrderedDict import items [as 别名]
#.........这里部分代码省略.........
if len(label) > 0: self.AddStaticText(label=label)
sName = name
if len(sName) == 0: sName = 'TextCtrl_' + FixName(label)
iStyle = style
if sName == 'TextCtrl_Password': iStyle |= wx.TE_PASSWORD
aSize = size
if aSize == wx.DefaultSize: aSize = (300, 21)
txt = wx.TextCtrl(parent=self, id=id, pos=pos, size=aSize, style=iStyle, name=sName)
txt.SetMaxLength(0)
txt.SetValue(value)
# sValue = unicode(value)
# txt.SetValue(sValue)
#txt.SetSize((2 * (txt.GetSize()[0]), txt.GetSize()[1]))
# print txt.GetSize()
self.Sizers[self.band].Add(txt, 1, wx.ALIGN_LEFT | wx.ALIGN_TOP)
self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1))
self.Bind(wx.EVT_TEXT, self.DefaultHandler, id=txt.GetId())
self.Bind(wx.EVT_TEXT_MAXLEN, self.DefaultHandler, id=txt.GetId())
# self.Bind(wx.EVT_KEY_DOWN, self.DefaultHandler, id=txt.GetId())
self.Controls[sName] = txt
return txt
# end def
def DefaultHandler(self, event):
# print 'event', str(event), 'id', event.GetId(), 'type', event.GetEventType()
iEventID = event.GetId()
iEventType = event.GetEventType()
oWindow = event.GetEventObject()
iID = oWindow.GetId()
#print 'event', event, 'eventID', iEventID, 'eventType', iEventType, 'windowID', iID
oParent = oWindow.GetParent()
# for control in self.Controls.keys():
# window = self.FindWindowByName(control)
for control, window in self.Controls.items():
try: result = window.GetValue()
except:
try: result = window.GetSelection()
except:
try: result = window.GetLabel()
except:
try: result = window.GetSelections()
except: result = None
self.Results[control] = result
sName = event.GetEventObject().GetName()
if self.ini and IsFocusEvent(event):
sSection = self.GetTitle()
sIni = self.ini
sValue = win32api.GetProfileVal(sSection, sName, '', sIni)
i = sValue.find(',')
# if i >= 0: sValue = sValue[i + 1:].strip()
# print sIni, sSection, sName, sValue
self.SetStatus(sValue)
if self.CustomHandler: return self.CustomHandler(self, event, sName)
# self.Close()
# if self.IsModal() and IsCloseEvent(event): self.EndModal(iID)
if self.IsModal() and not IsFocusEvent(event) and sName.startswith('Button_'): self.EndModal(iID)
# end def
def Complete(self, buttons = ['OK', 'Cancel'], index=0, handler=None, statusbar=True, ini=GetIni(), idle=False):
if len(buttons) > 0: self.AddButtonBand(buttons=buttons, index=index, handler=handler)
else: self.CustomHandler = handler
# self.Bind(wx.EVT_INIT_DIALOG, Activator)
self.Bind(wx.EVT_INIT_DIALOG, self.DefaultHandler)
self.Bind(wx.EVT_SHOW, self.DefaultHandler)
示例7: __init__
# 需要导入模块: from odict import OrderedDict [as 别名]
# 或者: from odict.OrderedDict import items [as 别名]
class Open:
kind = 'open'
number = 1
def __init__(self, bgpid, asnum, holdtime=180, version=4):
self.version = version
self.holdtime = holdtime
self.asnum = asnum
self.bgpid = bgpid
self.caps = OD()
self.params = OD()
def from_bytes(cls, bytes):
self = cls(None, None)
assert len(bytes) >= 10, "open message must have 10 bytes"
self.version, self.asnum, self.holdtime, bgpid, paramlen = struct.unpack_from('!BHH4sB', bytes)
self.bgpid = socket.inet_ntoa(bgpid)
assert len(bytes) == 10 + paramlen, "message too short?"
offset = 10
while offset < len(bytes):
type, plen = struct.unpack_from('BB', bytes, offset)
offset += 2
value = bytes[offset:offset+plen]
offset += plen
if type==2:
# capabilities
idx = 0
while idx < len(value):
kind, clen = struct.unpack_from('BB', value, idx)
idx += 2
cap = value[idx:idx+clen]
idx += clen
if kind==1:
kind = 'mbgp'
iidx = 0
afi, reserved, safi = struct.unpack_from('!HBB', cap)
cap = dict(afi=afi, safi=safi)
elif kind==2:
kind = 'refresh'
elif kind==64:
kind = 'graceful-restart'
elif kind==65:
kind = '4byteas'
cap, = struct.unpack('!I', cap)
if kind in self.caps:
self.caps[kind].append(cap)
else:
self.caps[kind] = [cap]
else:
self.params[type] = value
return self
from_bytes = classmethod(from_bytes)
def encode(self):
params = ''
for k,v in self.params.items():
params += struct.pack('BB', k, len(v))
params += v
for c,vv in self.caps.items():
if c=='mbgp':
c = 1
elif c=='refresh':
c = 2
elif c=='graceful-restart':
c = 64
elif c=='4byteas':
c = 65
for v in vv:
if c==1:
v = struct.pack('!HH', v['afi'], v['safi'])
elif c==65:
v = struct.pack('!I', v)
cap = struct.pack('BB', c, len(v)) + v
params += struct.pack('BB', 2, len(cap)) + cap
bgpid = socket.inet_aton(self.bgpid)
return struct.pack('!BHH4sB', self.version, self.asnum, self.holdtime, bgpid, len(params)) + params
def __str__(self):
s = 'Open message ver=%s as#=%s hold=%s peer=%s' % (
self.version,
self.asnum,
self.holdtime,
self.bgpid,
)
for p,v in self.params.items():
s += ' param %s=%r' % (p,v)
#.........这里部分代码省略.........