嵌套dict和for循环中的python字符串格式

时间:2016-12-27 22:38:26

标签: python string-formatting

使用以下词典,我正在尝试创建字符串。

query_args= {"columns":{ "investingcom":"datetime, actual, forecast, previous",
                        "bloomberg":"datetime, Actual, `Surv(M)`, Prior",
                        "ft":"datetime, actual, forecast, prior"},
             "table":{"investingcom":"`all-data`.`indicators`",
                     "bloomberg":"`all-data`.`indicators-bloomberg`",
                      "ft":"`all-data`.indicators_ft"},
             "country":{"investingcom":"\"US\"",
                     "bloomberg":"\"US\"",
                      "ft":"\"United States\""},
             "name":{"investingcom":"\"Average Hourly Earnings (MoM)\"",
                     "bloomberg":"\"Average Hourly Earnings MoM\"",
                      "ft":"\"Average Hourly Earnings %% m/m\""}
                     }

我需要创建3个字符串,因此使用for循环:

for ind_source in ["investingcom", "bloomberg", "ft"]:
    print('SELECT {columns[ind_source]} FROM {table[ind_source]} \
    WHERE country={country[ind_source]} AND name={name[ind_source]}'.format(**query_args))

然而,这会返回错误:

KeyError: 'ind_source'

有关如何使该实施成功的任何建议吗?

4 个答案:

答案 0 :(得分:1)

我不熟悉你在你的例子中尝试的方式(尽管可能通过一些调整来这样做。但是,我会这样做的方式类似于以下内容:

query_args= {"columns":{ "investingcom":"datetime, actual, forecast, previous",
                        "bloomberg":"datetime, Actual, `Surv(M)`, Prior",
                        "ft":"datetime, actual, forecast, prior"},
             "table":{"investingcom":"`all-data`.`indicators`",
                     "bloomberg":"`all-data`.`indicators-bloomberg`",
                      "ft":"`all-data`.indicators_ft"},
             "country":{"investingcom":"\"US\"",
                     "bloomberg":"\"US\"",
                      "ft":"\"United States\""},
             "name":{"investingcom":"\"Average Hourly Earnings (MoM)\"",
                     "bloomberg":"\"Average Hourly Earnings MoM\"",
                      "ft":"\"Average Hourly Earnings %% m/m\""}
                     }

for ind_source in ["investingcom", "bloomberg", "ft"]:
    print('SELECT {} FROM {} \
    WHERE country={} AND name={}'.format(
        query_args['columns'][ind_source],
        query_args['table'][ind_source],
        query_args['country'][ind_source],
        query_args['name'][ind_source],
    ))

答案 1 :(得分:1)

我会尝试以下方法:

for ind_source in ["investingcom", "bloomberg", "ft"]:
     print(
         ("SELECT {columns[%(ind_source)s]} FROM {table[%(ind_source)s]}"
          "WHERE country={country[%(ind_source)s]} AND "
          "name={name[%(ind_source)s]}" % { 'ind_source': ind_source })
     .format(**query_args))

基本上连续使用两个format操作来获取所需的查询。

答案 2 :(得分:0)

怎么样:

for ind_source in ["investingcom", "bloomberg", "ft"]:
    print(('SELECT {columns[' +ind_source + ']} FROM {table[' + ind_source + ']} \
    WHERE country={country[' + ind_source + ']} AND name={name[' + ind_source + ']}').format(**query_args))

如果您将'ind_source'放在字符串中,则格式化时会在'ind_source'字典中搜索密钥query_args。这个字典没有那个键,因此就是错误。 而是将字符串与for循环中的当前值ind_source连接起来。

答案 3 :(得分:0)

不要尝试复杂的格式,请先尝试过滤数据,以获得更清晰的格式字符串和可读性。

query_args= {"columns":{ "investingcom":"datetime, actual, forecast, previous",
                        "bloomberg":"datetime, Actual, `Surv(M)`, Prior",
                        "ft":"datetime, actual, forecast, prior"},
             "table":{"investingcom":"`all-data`.`indicators`",
                     "bloomberg":"`all-data`.`indicators-bloomberg`",
                      "ft":"`all-data`.indicators_ft"},
             "country":{"investingcom":"\"US\"",
                     "bloomberg":"\"US\"",
                      "ft":"\"United States\""},
             "name":{"investingcom":"\"Average Hourly Earnings (MoM)\"",
                     "bloomberg":"\"Average Hourly Earnings MoM\"",
                      "ft":"\"Average Hourly Earnings %% m/m\""}
                     }

for ind_source in ["investingcom", "bloomberg", "ft"]:
    args = {x: query_args[x][ind_source] for x in query_args}
    print('SELECT {columns} FROM {table} \
    WHERE country={country} AND name={name}'.format(**args))