簡體   English   中英

使用循環更新字典

[英]Dictionary update using a loop

我不明白為什么我的字典沒有更新。 如果我輸入兩個名字,例如JoeJosh ,那么我希望輸出為'name : Joe, name: Josh' ,但目前結果是'name: Josh'

我怎樣才能正確地做到這一點?

names_dic = {}
print("Enter the number of friends joining (including you):")
num_people = int(input())
print("Enter the name of every friend (including you), each on a new line:")
if num_people == 0:
    print("No one is joining for the party")
else:
    for _ in range(num_people):
        names = str(input())
        another_dict = {'name': names}
        names_dic.update(another_dict)
print(names_dic)

您正在覆蓋字典的內容,因為您始終使用相同的鍵。 如果你想將你的朋友存儲在一個列表中,你可以使用一個字典列表:

names_list = []
print("Enter the number of friends joining (including you):")
num_people = int(input())
print("Enter the name of every friend (including you), each on a new line:")
if num_people == 0:
    print("No one is joining for the party")
else:
    for _ in range(num_people):
        names = str(input())
        names_list.append({'name': names})
print(names_list)

有了喬和喬希,你就會得到

[{'name': 'Joe'}, {'name': 'Josh'}]

另一個想法是將名稱作為鍵

names_dic = {}
print("Enter the number of friends joining (including you):")
num_people = int(input())
print("Enter the name of every friend (including you), each on a new line:")
if num_people == 0:
    print("No one is joining for the party")
else:
    for _ in range(num_people):
        names = str(input())
        another_dict = {names: 'Joins the party'}
        names_dic.update(another_dict)
print(names_dic)

有了喬和喬希,你就會得到

{'Joe': 'Joins the party', 'Josh': 'Joins the party'}

鍵值在字典中必須是唯一的,但您有多個“名稱”鍵。 認為您想要的是一個集合,它將保留您添加到其中的每個名稱的一個副本。

暫無
暫無

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

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