使用字典理解为值创建不同长度的字典

时间:2014-09-07 03:05:23

标签: python python-2.7

这是输入字符串:

 visa = (u'GPIB0::5::INSTR', u'GPIB0::3::INSTR', u'ASRL1::INSTR', u'ASRL2::INSTR')

我的代码是字典理解中的生成器,如下所示:

  {comm : node for comm, node in (instance.split('::')[0:2] for instance in visa)}

当前输出:

{u'ASRL1': u'INSTR', u'ASRL2': u'INSTR', u'GPIB0': u'3'}

期望的输出:

{'ASRL1': 'INSTR', 'ASRL2': 'INSTR', 'GPIB0': (5, 3)}

基于字典/生成器方法的任何方式吗?

干杯, 我

1 个答案:

答案 0 :(得分:1)

您可以使用defaultdict

>>> import collections
>>> d = collections.defaultdict(list)
>>> for item in visa:
...     comm, node = item.split('::')[0:2]
...     d[comm].append(node)

然后,您可以将其转换为所需的数据结构,如下所示:

>>> {key: (value[0] if len(value) == 1 else tuple(value)) for key, value in d.items()}
{u'ASRL2': u'INSTR', u'ASRL1': u'INSTR', u'GPIB0': (u'5', u'3')}