您尚未描述用户可以接受的内容,但是,您可以使用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