将作业转换为dict

时间:2017-10-18 12:20:10

标签: python

我有很多很难分配的作业:

definition = ['basename', 'dirname', 'supports_unicode_filenames']
condition = ['isabs', 'isdir', 'isfile', 'islink', 'ismount']
.
.
.

打算将它们转换成dict,避免重复输入:

{'definition': ['basename', 'dirname', 'supports_unicode_filenames'],
 'condition': ['isabs', 'isdir', 'isfile', 'islink', 'ismount'] ...}

我试图将它们封装在课堂上。

class OsPath:
    definition = ['basename', 'dirname', 'supports_unicode_filenames']
    condition = ['isabs', 'isdir', 'isfile', 'islink', 'ismount']

使用控制台

In [125]: dt = dict(vars(OsPath))
In [127]: {i:dt[i] for i in dt if not i.startswith('__')}
Out[127]:
{'condition': ['isabs', 'isdir', 'isfile', 'islink', 'ismount'],
 'definition': ['basename', 'dirname', 'supports_unicode_filenames']}

如何在快捷方式中执行此操作?

3 个答案:

答案 0 :(得分:5)

你可以这样做:

definition = ['basename', 'dirname', 'supports_unicode_filenames']
condition = ['isabs', 'isdir', 'isfile', 'islink', 'ismount']
d = {'definition': definition, 'condition': condition }

请注意,您应该避免使用变量名dict,它是内置对象。

但说实话,如果你大规模地这样做,你所要做的并不是好的做法。你应该重新考虑你的对象的设计。

答案 1 :(得分:0)

这可能是你想要的:

(layerSize + 1, nextLayerSize)

答案 2 :(得分:0)

使用SimpleNamespace

from types import SimpleNamespace
sn = SimpleNamespace(
definition = ['basename', 'dirname', 'supports_unicode_filenames'],
condition = ['isabs', 'isdir', 'isfile', 'islink', 'ismount'],
)

输出:

In [44]: sn
Out[44]: namespace(condition=['isabs', 'isdir', 'isfile', 'islink', 'ismount'], definition=['basename', 'dirname', 'supports_unicode_filenames'])

In [45]: vars(sn)
Out[45]:
{'condition': ['isabs', 'isdir', 'isfile', 'islink', 'ismount'],
 'definition': ['basename', 'dirname', 'supports_unicode_filenames']}

In [17]: dict(definition = ['basename', 'dirname', 'supports_unicode_filenames'],condition = ['isabs', 'isdir'
    ...: , 'isfile', 'islink', 'ismount'])
Out[17]: 
{'definition': ['basename', 'dirname', 'supports_unicode_filenames'],
 'condition': ['isabs', 'isdir', 'isfile', 'islink', 'ismount']}