2016-04-13 39 views
-1

我在做一個項目,但是有一個問題,我碰到的,而使用字典,更具體怎麼添加一個條目如何添加到字典中使用用戶輸入

thing = {'a':1, 'b':2, 'c':3} 
thing.update(input('add more')) 
print(thing) 

我得到的問題當我嘗試添加到這個是:ValueError: dictionary update sequence element #0 has length 1; 2 is required。那麼我需要怎樣將信息放入字典中才能更新?到目前爲止,我嘗試過「d [4]」,「d 4」和「d:4」。

+2

'update'需要字典作爲一個參數,而不是一個字符串。 –

+0

這些引用僅僅是爲了證明我已經嘗試過它們,當我輸入它們時,我沒有包括引號 –

+0

只需分割輸入並直接添加它,例如:'k,v = input('add more ')。分裂(); thing [k] = int(v)',那麼輸入'「d 4」'會導致'thing ['d'] = 4'。 – AChampion

回答

0

如果你的目標是添加一個元素,你可以做這樣的事情:

thing['d'] = 4 

替代輸入在合適的地方。

+0

事情是我想要求用戶自己添加它 –

+0

對。這是執行它的語法(而不是擴展),而無需更多地瞭解您期望用戶輸入的樣子。您需要解析用戶輸入(根據您期望他們輸入的方式),然後將輸入的鍵替換爲「D」,將輸入的值替換爲「4」。 – Christian

1

您必須使用大括號將您的輸入轉換爲字典({ })。您可以拆分輸入,以便您有一個包含您的密鑰的字符串和一個包含您的值的字符串。

例如,如果你想增加其賦值爲d:4你可以使用字符串input

key, val = your_input.split(':') 
thing.update({key:val}) 

這是因爲dict.update功能需要一個字典作爲參數。

+0

這將如何工作? '{}'是一個字典字面值,不包含字符串。 – AChampion

+0

@AChampion你是對的,我相應地編輯了我的答案 – colelemonz

+1

'tuple'賦值也非常有用:'key,val = input.split(':')'(儘管我不會使用一個名爲'input'的變量) – AChampion

1

您尚未描述用戶可以接受的內容,但是,您可以使用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} 
-1
dictionary = {'Big brother':'Onii-chan', 'Big sister': 'Onee-sama', 'Hello': 'Konichiwa', 'Master': 'Sensei', 'Good Morning': 'Ohayo', 'Senior': 'Senpai', 'Ocean': 'Kaiyou/Umi','Darkness': 'Yami', 'Light': 'Hikari', 'Sky':'Sora','x':[1,2]} 

keep_going = 'Y' 


while keep_going == 'y' or keep_going == 'Y': 

print(dictionary.keys()) 

x = input("Pick one out of the list to see the translation in japanese") 

print(dictionary[x]) 

keep_going = input('would you like another one? (Y for Yes): ') 
相關問題