从内部有列表的字典中打印句子提取信息的方法如下:
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.
这样,我们就可以从内部有列表的字典中打印句子并提取信息了。
腾讯云相关产品和产品介绍链接地址:
云+社区技术沙龙[第16期]
企业创新在线学堂
云+社区技术沙龙[第7期]
【产研荟】直播系列
Elastic 中国开发者大会
云+社区技术沙龙[第10期]
云+社区技术沙龙[第12期]
腾讯云GAME-TECH沙龙
云+社区开发者大会 武汉站
领取专属 10元无门槛券
手把手带您无忧上云