簡體   English   中英

如何僅從詞典中打印一項

[英]How to print only 1 item from a dictionary

我最近才剛剛開始學習Python,通常可以在網上找到我的問題的答案,但似乎無法為該問題找到正確的解決方案。 我創建了一個包含3個聯系人的字典,我想使用if語句從列表中打印1個聯系人。

contacts = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781
}

if "John" in contacts: print ("Contact details: %s %i" % contacts.items()[0])

這是我正在尋找的輸出:

聯系方式:約翰938477566

但是我不斷得到這個

追溯(最近一次通話):文件“ C:\\ Users \\ user \\ Documents \\ asega \\ python \\ objectsclasses \\ exercise3.py”,第31行,正在打印(“聯系方式:%s%i”%contact.items( )[0])TypeError:'dict_items'對象不支持索引

謝謝

contacts.items()返回一對鍵值。 就您而言,那就像

(("John", 938477566), ("Jack", 938377264), ("Jill", 947662781))

除了在python 3中,這就像一個生成器而不是一個列表。 因此,如果要為其編制索引,則必須執行list(contacts.items()) ,這將說明您的錯誤消息。 但是,即使您如上所述進行list(contacts.items())[0] ,也將獲得第一對鍵值。

您要嘗試做的是獲取一個鍵的值(如果該鍵存在),而contacts.get(key, value_if_key_doesnt_exist)會為您執行此操作。

contact = 'John'
# we use 0 for the default value because it's falsy,
# but you'd have to ensure that 0 wouldn't naturally occur in your values
# or any other falsy value, for that matter.
details = contacts.get(contact, 0)
if details:
    print('Contact details: {} {}'.format(contact, details))
else:
    print('Contact not found')

你可以這樣 如果您確定字典中有“ John”,則不需要if語句。 用其他方式,您可以編寫它。

contacts = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781
}
print("Contact details: %s %i" % ("John", contacts["John"]))

不需要檢查中if條件只是使用get得到相應的值,並返回-1如果鍵不存在

contacts = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781
}

contacts.get('John',-1) # -1 will be returned if key is not found

打印格式

name_to_search='John'
print("Contact details: %s %i" % (name_to_search, contacts.get(name_to_search,-1)))

要么

name_to_search='John'
print("Contact details: {} {}" .format(name_to_search, contacts.get(name_to_search,-1)))

首先,它的字典不是列表,您可以通過建立索引來訪問列表中的元素,而在字典中是不可能的,您可以通過鍵來訪問元素

contacts = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781
}

for k,v in contacts.items():
    print(k,v)

或聯系人['John'],您可以訪問該值

字典不支持索引,因此要打印“ John”,您不能對其進行索引,但是以下代碼可能會出現以下字詞:

if "John" in contacts:
   print("Contact details:","John",contacts["John"])

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM