简体   繁体   English

如何获取此代码以打印我想要的内容?

[英]How do I get this code to print what I want?

I need to print我需要打印

"Topic {topic} was created by {creator} on {date_added}." “主题 {topic} 由 {creator} 在 {date_added} 创建。” using a FOR loop.使用 FOR 循环。 I have entered all the required information into dictionaries as per the assignment.我已根据作业将所有必需的信息输入字典。

I don't know what else to try I am new.我不知道还能尝试什么我是新手。 Looking for help with dictionaries and FOR loops.寻求有关字典和 FOR 循环的帮助。

    #1.1
    topic1 = {
        "date_added": (2019,9.1),
        "creator": "Mark Scorgie"
    }

    topic2 = {
        "date_added": (2019,9.1),
        "creator": "Mark Scorgie"
    }

    topic3 = {
        "date_added": (2019,9.1),
        "creator": "Mark Scorgie"
    }

    #1.2
    topics = {
        "climbing": topic1,
        "travelling": topic2,
        "swimming": topic3
    }

    #2
    for topic, date_added, creator in sorted(topics.keys()): 
        print(f"Topic {topic} was created on {date_added} by {creator}")

I am getting an error message that {date_added} is not defined.我收到一条错误消息,指出 {date_added} 未定义。 I have tried for topic in sorted(topics.items()) and for topic in sorted(topics.keys()) but no luck.我已经尝试过 sorted(topics.items())的主题和 sorted(topics.keys()) 中的主题,但没有运气。 Not sure how to define date_added and creator in each iteration of the loop.不确定如何在循环的每次迭代中定义 date_added 和 creator。

The first problem with your code is you are using a tuple in the "date_added" key.It should be您的代码的第一个问题是您在“date_added”键中使用了一个元组。它应该是

topic1 = {
    "date_added": "2019,9.1",
    "creator": "Mark Scorgie"
}
for key, value in topics.items():
    print(f"Topic {key} was created on {value['date_added']} by {value['creator']}")

The key will be the name of the topic and the value will be the dictionary contain the info of that topic.键将是主题的名称,值将是包含该主题信息的字典。 You can access the value of a dict by using dict[key_name]您可以使用 dict[key_name] 访问 dict 的值

For dict objects, you can do someDict.items() to separate the key value and the element value.对于 dict 对象,您可以执行 someDict.items() 来分隔键值和元素值。

Therefore, you can use for loop to access the key and the value by:因此,您可以使用 for 循环通过以下方式访问键和值:

someDict = {
    "abc" : "123"
}

for key, value in someDict.items():
    print(key)                #output: abc
    print(value)              #output: 123

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

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