Python 添加到字典循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26263682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:17:20  来源:igfitidea点击:

Python Add to dictionary loop

pythondictionary

提问by bugsyb

This function is supposed to add a name and number to the dictionary 'phoneBook' when I run the loop, but for some reason I can't get it to work. Any ideas on why not? Thanks a lot!

当我运行循环时,这个函数应该向字典“phoneBook”添加一个名字和号码,但由于某种原因我无法让它工作。关于为什么不的任何想法?非常感谢!

 phoneBook = dict()
    def addNumber(name, number):
        for i in phoneBook:
            if i == name:
                print 'error'
            else:
                phoneBook[name] = number

回答by Cory Kramer

You don't really need the loop at all, you can just use the inkeyword to check the name against the existing keys in the dictionary.

您根本不需要循环,您可以使用in关键字根据字典中的现有键检查名称。

phoneBook = dict()
def addNumber(name, number):
    if name in phoneBook:
        print 'error'
    else:
        phoneBook[name] = number

回答by Joran Beasley

why bother

何苦

people = ((data["name"],data["number"]) for data in json.loads(some_list)[::-1])
phoneBook = dict(people)

this will run in reverse order through the list so the first occurrence of the name will be the one stored in the dictionary

这将在列表中以相反的顺序运行,因此名称的第一次出现将是存储在字典中的名称

it takes longer to check than to just insert it ... even if it ends up over written

检查比插入它需要更长的时间......即使它最终被覆盖

to answer your question however

然而要回答你的问题

your original code did not work because your else was inside the forloop essentially adding the entry if any name in the book did not match the name being inserted

您的原始代码不起作用,因为您的 else 位于 forloop 中,如果书中的任何名称与插入的名称不匹配,则基本上会添加条目

you can fix it easily enough, by exiting the function when a match is found... and not adding the name to the dictionary until you have checked all names

您可以通过在找到匹配项时退出该函数来轻松修复它......并且在您检查所有名称之前不要将名称添加到字典中

phoneBook = dict()
def addNumber(name, number):
    for i in phoneBook:
        if i == name:
            print 'error'
            return
    phoneBook[name] = number

addNumber("james",56)
addNumber("Tommy",26)
addNumber("james",77)