简体   繁体   English

您如何使用添加到字典中?

[英]How do you add to dictionary using append?

I've almost at my end goal with this. 为此,我几乎达到了最终目标。 I want the user to type in a list of names and then the position of the word to be saved in the dictionary if the word is not already been saved. 我希望用户键入名称列表,然后输入要保存在字典中的单词的位置(如果尚未保存该单词)。 For example Ali, Dan, Martin, Ali will read 1 2 3 1 . 例如,Ali,Dan,Martin,Ali将读取1 2 3 1。

Names= input("Type all names you want to include: ")
##str.casefold
Names = Names.split()
AllWords = len(Names)
dict = {}
pos=0
for j in enumerate(Names):
    for j in range(AllWords):
        if Names not in dict:
          dict.update(key,Names)
print(Dictionary)

Expected output would be: 预期输出为:
Matt Mike Jerry Jon Sarah Matt 1 2 3 4 5 1 #names and positions Matt Mike Jerry Jon Sarah Matt 1 2 3 4 5 1#姓名和职位

您可以简单地执行以下操作,以便在现有或空字典中添加更多键值对。

Dictionary[key] = value

字典没有append(value)方法,请改用update({key: value})

As far as i know Dictionaries in python does not have any method called append , instead make use of update 据我所知,python中的Dictionary没有任何称为append的方法,而是利用update

dict.update({key:value})  or dict[key] = value

in the second case if key is not present it will add a new entry, if key is there it will update the value corresponding to that key. 在第二种情况下,如果不存在密钥,它将添加一个新条目;如果存在密钥,它将更新与该密钥相对应的值。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM