简体   繁体   English

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

[英]python string formatting within nested dict and for loop

With the following dictionnary, i am trying to implement creating of strings. 使用以下字典,我试图实现字符串的创建。

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\""}
                     }

There is 3 strings i need to create, hence the use of a for loop: 我需要创建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))

However this returns an error: 但是,这将返回错误:

KeyError: 'ind_source'

Any suggestion how to make that implementation successful? 任何建议如何使该实施成功?

I am not familiar with doing it the way you try in your example (though it may be possible to do it that way with some tweaking. However, the way I would do it is something like the following: 我对您在示例中尝试的方式不熟悉(尽管可以通过一些调整来做到这一点。但是,我的方式类似于以下内容:

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],
    ))

I would try the following: 我会尝试以下方法:

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))

essentially using two format operations in succession to get the queries you want. 本质上是连续使用两种format操作来获取所需的查询。

How about: 怎么样:

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))

If you put 'ind_source' inside the string, when formatting it will search for the key 'ind_source' in the query_args dictionary. 如果你把'ind_source'格式化字符串,里面时,它会搜索键'ind_source'query_args字典。 This dictionary doesn't have that key, thus that error. 该词典没有该键,因此没有该错误。 Instead concatenate the string with the current value of ind_source in the for loop. 而是在for循环中将字符串与ind_source的当前值连接在一起。

Instead of trying to do a complicated format, try filtering your data first for a cleaner format string and readability. 不要尝试做复杂的格式,而是先过滤数据以获得更清晰的格式字符串和可读性。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM