您尚未描述用戶可以接受的內容,但是,您可以使用ast.literal_eval()
。這要求用戶輸入一個有效的Python字典。
>>> from ast import literal_eval
>>> thing = {'a':1, 'b':2, 'c':3}
>>> thing.update(literal_eval(input('add more: ')))
add more: {'d':4, 'e':5, 'z':26}
>>> thing
{'a': 1, 'c': 3, 'z': 26, 'd': 4, 'b': 2, 'e': 5}
雖然輸入不是非常用戶友好。
您可以讓用戶輸入空格分隔的鍵和值,例如a 1 e 5 z 26
。然後將其轉換成一個字典和執行更新:
>>> thing = {'a':1, 'b':2, 'c':3}
>>> it = iter(input('add more: ').split())
add more: a 10 y 25
>>> thing.update(dict(zip(it, it)))
>>> thing
{'y': '25', 'c': 3, 'b': 2, 'a': '10'}
或者你可以使用:
各項目之間的分隔鍵和值,用空間:
>>> thing = {'a':1, 'b':2, 'c':3}
>>> thing.update(dict(s.split(':') for s in input('add more: ').split()))
add more: a:10 z:26
>>> thing
{'a': '10', 'c': 3, 'z': '26', 'b': 2}
'update'需要字典作爲一個參數,而不是一個字符串。 –
這些引用僅僅是爲了證明我已經嘗試過它們,當我輸入它們時,我沒有包括引號 –
只需分割輸入並直接添加它,例如:'k,v = input('add more ')。分裂(); thing [k] = int(v)',那麼輸入'「d 4」'會導致'thing ['d'] = 4'。 – AChampion