python - 缩短在字典中打印单个值

标签 python dictionary

我刚刚为 python 编写了这段简短的代码。这是学校的时间表。我不经常使用字典,因为这是我总是感到困惑的部分。

我在代码中想要的是 print(monday["Period 1"])我重复 5 次,要清理,所以它会只需要一行代码。

我在想也许我应该使用 for 循环。但是由于我并没有真正使用 for 循环,所以我不知道如何正确使用它们。除了一两次。

这是我到目前为止所做的代码。

monday = {"P1" : "1 - English",
      "P2" : "2 - Maths",
      "P3" : "3 - PE",
      "P4" : "4 - Computing",
      "P5" : "5 - Computing"}

choice_day = input("What day would you like to know what you have? ")
choice_period = input("What period? Or just type NO if you want to know the full day: ")

if choice_day == "monday" and choice_period == "NO":
    print(monday["P1"])
    print(monday["P2"])
    print(monday["P3"])
    print(monday["P4"])
    print(monday["P5"])

最佳答案

字典中所有值的列表作为monday.values()

存在
if choice_day == "monday" and choice_period == "NO":
    for v in monday.values():
        print v

或者您可以将列表中的每个值放入一个由换行符连接的字符串中:

if choice_day == "monday" and choice_period == "NO":
    print '\n'.join(monday.values())

如果它们应该是有序的,使用sorted:

if choice_day == "monday" and choice_period == "NO":
    print '\n'.join(sorted(monday.values()))

关于python - 缩短在字典中打印单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19013204/

相关文章:

python - SqlAlchemy:如何实现 DROP TABLE ... CASCADE?

python - 如何在不更改特定列的情况下对数据框中的数据进行重新采样?

python - 将字典列表转换为字典集列表

java - 在 Java 中迭代 Map<TypeA,Set<Type>> 并将其转换为 Map<Type B,Set<TypeA>>

jquery - 带有图像和表单的下拉菜单

python - 恢复 Pandas 中的默认显示上下文

Python:np.vectorize 返回 "float"

c# - 如果我有冗长的数据类型会有问题吗?

python - 如何将字符串转换为看起来已经是字典的字典?

python - 有没有办法在不创建类实例的情况下获取类实例属性?