2013-09-23 73 views
1

這個問題可能非常愚蠢,但我試圖用字典來迭代並返回結果。我知道如何迭代字典,但我想檢查輸入的密鑰是否存在於字典中,如果值存在或不存在,我希望程序打印。使用IF內部FOR循環的Python

class companyx: 

    def __init__(self,empid): 

     self.empid=empid 

    def employees(self): 

     employees={1:'Jane',2:'David',3:'Chris',4:'Roger'} 

     entered=self.empid 

     for emp in employees : 
      if emp == entered: 
       print ('Hi '+employees[emp] +' you are an employee of companyx.com') 
     print('You dont belong here') 

emp=companyx(2) 

emp.employees() 

當我傳遞一個參數,它是不是在字典中,我想要的功能打印「你不屬於這裏」

回答

2

使用in關鍵字來快速執行字典查找:

if entered in employees: 
    # the key is in the dict 
else: 
    # the key could not be found 
2

試試這個:

if entered in employees.keys(): 
    .... 
else: 
    .... 
+4

不需要'keys()':'如果輸入員工'。 – alecxe

1

無需一對循環 - 你只需要:

if entered in employees: 
    print 'blah' 
else: 
    print 'You do not belong here' 
8

最簡單的(也是最習慣的)方法來檢查密鑰是否在字典中是:

if entered in employees: 

以上代替for/if部分代碼。請注意,沒有必要明確遍歷字典,in運算符負責檢查成員資格。簡短而親切:)完整的代碼應該是這樣的:

def employees(self): 
    employees = {1:'Jane', 2:'David', 3:'Chris', 4:'Roger'} 
    if self.empid in employees: 
     print('Hi ' + employees[self.empid] + ' you are an employee of companyx.com') 
    else: 
     print("You don't belong here") 
+1

+1這種方式你不需要編寫循環部分(因爲它在後臺執行任何操作) – TehTris

+0

誤解,刪除評論+ downvote – MichaelvdNet

+0

是的,你可以邁克爾:'x = {'pie':'thon'};斷言('x'中的餡餅)'......呵呵你知道我的意思:) – TehTris

2

你並不需要翻翻字典,做迭代。你可以寫:

def employees(self): 

    employees={1:'Jane',2:'David',3:'Chris',4:'Roger'} 
    employee = employees.get(self.empid) 

    if employee: 
     print ('Hi ' + employee + ' you are an employee of companyx.com') 
    else: 
     print ('You dont belong here') 
2

最Python的方式做,這是剛剛嘗試查找和處理故障,如果它發生了:

try: 
    print('Hi '+employees[entered] +' you are an employee of companyx.com') 
except KeyError: 
    print('You dont belong here') 

沒有理由爲for循環;整個詞典的重點在於你可以一步到位,而不是必須遍歷按鍵並檢查每一個是否爲== key

您可以使用in來檢查密鑰是否存在,然後查找它。但這有點愚蠢 - 你在查找是否可以查看密鑰的關鍵。爲什麼不直接看鑰匙?

您可以通過使用get方法,它返回None做到這一點(或者你可以通過不同的默認值),如果鑰匙丟失:

name = employees.get(entered) 
if name: 
    print('Hi '+name +' you are an employee of companyx.com') 
else: 
    print('You dont belong here') 

但它的Easier to Ask Forgiveness than Permission。除了稍微更簡明,使用tryexcept明確指出找到名稱是正確的情況,應該是真實的,而不是發現它是例外情況。

+0

+1使用'try/except'的確是_the_ Pythonic方法來解決這個問題 –