2016-12-03 47 views
-1

我正在做作業的編程基礎1,我有與分配麻煩如何判斷Python字典是否包含給定的密鑰?我如何檢索關聯的值?

我工作的任務是在課上練習7.我堅持用問題3和4

  1. 假設變量dct引用一個字典。編寫一個if語句,用於確定 字典中是否存在關鍵字'James'。如果是,則顯示與該鍵關聯的值。 如果密鑰不在字典中,則顯示一條消息指示如此。

  2. 假設變量DCT引用的字典。編寫一個if語句,用於確定 字典中是否存在鍵'Jim'。如果是這樣,刪除'吉姆'及其相關值。

這是我做的。我不知道我是否有這個權利。任何人都可以解釋給我嗎?

def main(): 
    mydict={'a':1, 'b':2, 'c':3} 
    mydict = {} 
    mydict = {'James'} 
    mydict = {'Jim'} 

main() 
+5

你「寫if語句」?我在這裏沒有看到。你堅持什麼? – jtbandes

+0

這是一種笑話嗎?你沒有完成任務所要求的一件事。即使變量名稱是錯誤的。 – JJJ

+0

對不起,我只是不知道該怎麼做。我不明白作業。 –

回答

-1

Hi Poone Kricanakarin。

我相信這snipet可以回答你的問題數3:

dct = {"James1": 1, "Leon": 2, "Eva": 3} 
keys = dct.keys() # This is the main point to your answer 
James_in_keys = False 
for key in keys: 
    if key == "James": 
     print dct[key] 
     James_in_keys = True 
if not James_in_keys: 
    print "The key ""James"" is not in the dictionary" 

我猜你不明白的assigngment可能是因爲你不知道「鍵()」命令出現在下面的代碼並返回給你一個包含字典中所有鍵的列表。

我相信,有了這個,你可以很容易地ANSWEER問題4.

2
from __future__ import print_function # just for making sure that 
             # the below works for Python 2 and 3 

# print value associated with key 'James' in dct, if that key is in dct 
if 'James' in dct: 
    print(dct['James']) 
else: 
    print("'James' isn't a key in dct.") 

# delete key 'Jim' and associated value if in dct 
if 'Jim' in dct: 
    del dct['Jim'] 

查看詞典的部分在the official Python tutorialthe Python standard library documenation。另外,您可能需要閱讀if statements

相關問題