I need to print
"Topic {topic} was created by {creator} on {date_added}." using a FOR loop. 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.
#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. I have tried for topic in sorted(topics.items()) and for topic in sorted(topics.keys()) but no luck. Not sure how to define date_added and creator in each iteration of the loop.
The first problem with your code is you are using a tuple in the "date_added" key.It should be
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]
For dict objects, you can do someDict.items() to separate the key value and the element value.
Therefore, you can use for loop to access the key and the value by:
someDict = {
"abc" : "123"
}
for key, value in someDict.items():
print(key) #output: abc
print(value) #output: 123
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.