首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从字典中提取值并将其格式化为句子

问如何从字典中提取值并将其格式化为句子
EN

Stack Overflow用户
提问于 2020-07-01 06:03:25
回答 4查看 49关注 0票数 0

这就是我必须为这个问题做的,我不确定格式。这是基于python 3.4的,所以不能使用f‘字符串。

这就是问题所在:

创建一个函数,该函数接受一个字典作为参数,并返回一个包含城市相关事实的字符串。城市事实将需要从字典中提取三个属性:

代码语言:javascript
复制
name
population
continent

字符串的格式应该如下:X的人口为Y,位于Z中(其中X是城市名称,Y是人口,Z是城市所在的大陆)。示例

代码语言:javascript
复制
city_facts({
  name: "Paris",
  population: "2,140,526",
  continent: "Europe"
}) ➞ "Paris has a population of 2,140,526 and is situated in Europe"
city_facts({
  name: "Tokyo",
  population: "13,929,286",
  continent: "Asia"
}) ➞ "Tokyo has a population of 13,929,286 and is situated in Asia"*

这是我最初想出的方法,但它不起作用,因为Python3.4不存储字典值的顺序。

代码语言:javascript
复制
def city_facts(city):
    info = list(city.values())
    return '{} has a population of {} and is situated in {}'.format(info[0], info[2], info[1])

如何根据字典值填充空格?上面的代码无法工作,因为python3.4不存储字典值的顺序。基于Python3.4,我需要做些什么来解决这个问题?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-07-01 06:13:59

您可以使用如下键直接访问字典

代码语言:javascript
复制
city = {"name": "Paris", "population": "2,140,526", "continent": "Europe"}


def city_facts(city):
    return "{} has a population of {} and is situated in {}".format(
        city["name"], city["population"], city["continent"]
    )

print(city_facts(city))

输出:

代码语言:javascript
复制
Paris has a population of 2,140,526 and is situated in Europe
票数 1
EN

Stack Overflow用户

发布于 2020-07-01 06:16:57

您可以在str.format中使用关键字参数

代码语言:javascript
复制
city = {"name": "Paris", "population": "2,140,526", "continent": "Europe"}
print("{name} has a population of {population} and is situated in {continent}".format(**city))

打印:

代码语言:javascript
复制
Paris has a population of 2,140,526 and is situated in Europe
票数 0
EN

Stack Overflow用户

发布于 2020-07-01 06:30:07

也许这段代码可以帮助你。我将你的字典解构成一个列表,然后我做一个映射函数,让每个字典都有一个字符串。这是代码。

代码语言:javascript
复制
city_facts = [{
  "name": "Paris",
  "population": "2,140,526",
  "continent": "Europe"
},
{
  "name": "Tokyo",
  "population": "13,929,286",
  "continent": "Asia"
}]
# im not sure what version of python able to use format string like below
result = list(map(lambda data: f'{data["name"]} has a population of {data["population"]} and is situated in {data["continent"]}', city_facts))
# you can also use this format string for your version python 3.4
result = list(map(lambda data: '{} has a population of {} and is situated in {}'.format(data["name"],data["population"],data["continent"]), city_facts))
# the result will be a list type, if you want to print as a single string, you can make an iteration to the list
print(result)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62666804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档