python - 为什么我在 for 循环中收到无效语法错误?

标签 python dictionary syntax-error

我正在编写一个 python 程序来显示字典的元素,但是当我运行该程序时,我收到了无效语法错误。我在 for 循环的第三行到最后一行收到错误。有谁知道为什么会出现这个错误?

def main():
    my_contacts = {"Fred":7239591, "Mary":3841212, "Bob":3841212, \
               "Sarch":2213278}
    if 'Fred' in my_contacts:
        print('Number for Fred', my_contacts["Fred"])
    else:
        print("Fred is not in my_contacts list.")
    nameList = findName(my_contacts, 3841212)
    print("Names for 3841212:", end = " ")
    for name in nameList:
        print(name, end=" ")
    print()
    printAll(my_contacts)

def findName(contacts, number):
    nameList = []
    for name in contacts:
        if contacts[name]==number:
            nameList.append(name)
    return nameList

def printAll(contacts):
    print("All names and numbers")
    for key in sorted contacts:
        print(key.contacts[key])
main()

最佳答案

您的语法不正确。更改您的 printAll 函数,如下所示 -

def printAll(contacts):
    print("All names and numbers")
    for key in sorted(contacts):
        print(key, contacts[key])

关于python - 为什么我在 for 循环中收到无效语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50376287/

相关文章:

c# - 多键数据结构

python - 如何在字典中以原始顺序返回键

python - Python 中的泰尔 U 1/泰尔 U 2 预测系数公式

python - Sphinx 不改变版本号

python - 字典排序操作出错

c++ - 错误: invalid operands of types 'int' and '<unresolved overloaded function type>' to binary 'operator<='

mysql - MySQL中的语法错误,但是在创建ROLE时语法正确

带有下划线的Python lambda作为参数?

python - Matplotlib 应从 x 轴上的 0 开始,并且主要和次要刻度应指向轴内部

php - 我的 joomla 网站出现问题