簡體   English   中英

python dicts of dicts out of python dicts

[英]python dicts of dicts out of python dicts

我有預定義的字典,我需要一個函數來從幾個輸入字典中形成一個字典,其中鍵是輸入字典的名稱。

例如,我有以下內容:

double_left = {
    'left': 6
}

double_right = {
    'right': 6
}

輸出應該是:

>>> output_dicts
{'double_left': {'left': 6}, 'double_right': {'right': 6}}

我已經嘗試過: 如何在 Python 中創建嵌套的 dict? 但無法得出答案。

建議?

如果您想在不對頂級項目的名稱進行硬編碼的情況下動態執行此操作,則可以使用globals()和/或locals()按名稱獲取變量列表。 例如:

output = {}
for name, val in globals().items():
    # Skipping variables that aren't dicts, and special
    # variables starting with '_'
    if isinstance(val, dict) and not name.startswith('_'):
        output[name] = val

for name, val in locals().items():
    if isinstance(val, dict) and not name.startswith('_'):
        output[name] = val

或更緊湊:

output = {name:val for name, val in (list(locals().items()) +
                                     list(globals().items()))
          if isinstance(val, dict) and not name.startswith('_')}

做一本新字典就行了。

output_dict = {"double_left": double_left, "double_right": double_right}
print(output_dict)

就像你當前的字典有 'key': 'value' 對,你的值是 ints (6),你可以創建一個新的字典,鍵是字典的名稱,值是嵌套的字典。

output_dicts = {'double_left': double_left, 'double_right': double_right}

>>> output_dicts
{'double_left': {'left': 6}, 'double_right': {'right': 6}}

您也可以使用dict_name[new_key] = new_value 例如:

output_dicts['double_left'] = double_left
output_dicts['double_right'] = double_right

嘗試這個

Newdict = dict(double_left = { 'left': 6},double_right = 
{'right': 6})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM