我一直在尋找這個問題的答案,但我找不到。預先警告我是 Python 新手,所以提前為 noobiness 道歉:D。
這是我的字典:
dict = {'test_key': 'test_value', 'test_key2': 'test_value2'}
這是我想要實作的輸出:
dict = {'test_key': ['test_value'], 'test_key2': ['test_value2']}
在此先感謝您的幫助!
uj5u.com熱心網友回復:
您可以遍歷字典的專案并為其分配串列。
for key, value in dict.items():
dict[ key ] = [ value ]
uj5u.com熱心網友回復:
您可以使用字典理解:
dict = {key: [values] for key, values in dict.items()}
新的字典將是:
{'test_key':['test_value'],'test_key2':['test_value2']}
uj5u.com熱心網友回復:
if __name__ == '__main__':
dict = {'test_key': 'test_value', 'test_key2': 'test_value2'}
for key, value in dict.items():
dict[key] = [value]
for key,values in dict.items():
print(key)
print(values)
uj5u.com熱心網友回復:
您可以按照從最快到最慢的實施順序執行此操作的幾種方法:
字典理解:
{
k: [v] for k, v in dict.items()
}
簡單的:
for k, v in dict.items():
dict[k] = [v]
Python地圖():
dict(map(
lambda x: (x[0], [x[1]]), dict.items()
))
結果:
{'test_key':['test_value'],'test_key2':['test_value2']}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496477.html
