从内部有列表的字典中打印句子提取信息的方法如下:
data = {
"name": "John",
"age": 25,
"hobbies": ["reading", "swimming", "coding"]
}
sentence = "My name is {name}. I am {age} years old. My hobbies are {hobbies}."
hobbies_str = ", ".join(data["hobbies"]) # 将列表转换为字符串
print(sentence.format(name=data["name"], age=data["age"], hobbies=hobbies_str))
输出结果为:
My name is John. I am 25 years old. My hobbies are reading, swimming, coding.
data = {
"name": "John",
"age": 25,
"hobbies": ["reading", "swimming", "coding"],
"address": {
"city": "New York",
"country": "USA"
}
}
sentence = "My name is {name}. I am {age} years old. My hobbies are {hobbies}. I live in {city}, {country}."
hobbies_str = ", ".join(data["hobbies"]) # 将列表转换为字符串
print(sentence.format(name=data["name"], age=data["age"], hobbies=hobbies_str, city=data["address"]["city"], country=data["address"]["country"]))
输出结果为:
My name is John. I am 25 years old. My hobbies are reading, swimming, coding. I live in New York, USA.
这样,我们就可以从内部有列表的字典中打印句子并提取信息了。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云