2017-10-18 14 views
1

我處理一些variable = value風格日期:如何將`可變值對'日期與字典集成?

data_type = {'Number': ['int','bool','float','complex'], 
      'Literal':['str','None','bytes']} 
data_struture = {'Sequence':['list', 'tuple','bytearray'], 
       'Set': ['set', 'frozenset'], 
       'Map':'dict'} 
. 
. 
. 

Atempt將其納入與關鍵inoformation的字典同時避免重複打字varaibles, 與最終產出爲

{'data_struture': {'Map': 'dict', 
    'Sequence': ['list', 'tuple', 'bytearray'], 
    'Set': ['set', 'frozenset']}, 
'data_type': {'Literal': ['str', 'None', 'bytes'], 
    'Number': ['int', 'bool', 'float', 'complex']} 
    . 
    . 
    .} 

我試圖解決按照以下步驟將原始日期封裝到一個類中:

首先封裝:

class FormalLanguage: 
    data_type = {'Number': ['int','bool','float','complex'], 
      'Literal':['str','None','bytes']} 
    data_struture = {'Sequence':['list', 'tuple','bytearray'], 
        'Set': ['set', 'frozenset'], 
        'Map':'dict'} 

二來檢索類的屬性

In [135]: x = dict(vars(FormalLanguage)) 
In [136]: x 
Out[136]: 
{'__dict__': <attribute '__dict__' of 'FormalLanguage' objects>, 
'__doc__': None, 
'__module__': '__main__', 
'__weakref__': <attribute '__weakref__' of 'FormalLanguage' objects>, 
'data_struture': {'Map': 'dict', 
    'Sequence': ['list', 'tuple', 'bytearray'], 
    'Set': ['set', 'frozenset']}, 
'data_type': {'Literal': ['str', 'None', 'bytes'], 
    'Number': ['int', 'bool', 'float', 'complex']}} 

三來篩選合格

In [137]: { i:x[i] for i in x if not i.startswith('__')} 
Out[137]: 
{'data_struture': {'Map': 'dict', 
    'Sequence': ['list', 'tuple', 'bytearray'], 
    'Set': ['set', 'frozenset']}, 
'data_type': {'Literal': ['str', 'None', 'bytes'], 
    'Number': ['int', 'bool', 'float', 'complex']}} 

最後得到的結果。

如何直接整合它們?

回答

1

你可以試試這個:

final_dict = {"data_structure":data_struture, "data_type":data_type} 

輸出:

{'data_structure': {'Map': 'dict', 'Set': ['set', 'frozenset'], 'Sequence': ['list', 'tuple', 'bytearray']}, 'data_type': {'Literal': ['str', 'None', 'bytes'], 'Number': ['int', 'bool', 'float', 'complex']}} 

或者,您也可以通過**kwargs通過他們:

def data(**kwargs): 
    final_data = kwargs 
    print(final_data) 

data(data_structure = data_struture, data_stype=data_type) 
+0

它的工作原理,我得到一個突然的想法,複製到編輯器,那麼所有'='和'替換:' - : - –

0

使用SimpleNamespace

from types import SimpleNamespace 
sn = SimpleNamespace(
data_type = {'Number': ['int','bool','float','complex'], 
      'Literal':['str','None','bytes']}, 
data_struture = {'Sequence':['list', 'tuple','bytearray'], 
       'Set': ['set', 'frozenset'], 
       'Map':'dict'} 

) 它輸出:

In [47]: sn 
Out[47]: namespace(data_struture={'Sequence': ['list', 'tuple', 'bytearray'], 'Set': ['set', 'frozenset'], 'Map': 'dict'}, data_type={'Number': ['int', 'bool', 'float', 'complex'], 'Literal': ['str', 'None', 'bytes']}) 
In [48]: vars(sn) 
Out[48]: 
{'data_struture': {'Map': 'dict', 
    'Sequence': ['list', 'tuple', 'bytearray'], 
    'Set': ['set', 'frozenset']}, 
'data_type': {'Literal': ['str', 'None', 'bytes'], 
    'Number': ['int', 'bool', 'float', 'complex']}} 
相關問題