如何打印许多变量的名称及其值

时间:2019-10-27 03:51:34

标签: python-3.x

我有很多json代码。我将所需的我的值分配给了超过10个变量。现在,我想使用print打印所有variable_name = value的方式来完成此任务

遵循预期的输出

variable_name_1 = car
variable_name_2 = house
variable_name_3 = dog

更新了我的代码示例

leagues = open("../forecast/endpoints/leagues.txt", "r")
leagues_json = json.load(leagues)
data_json = leagues_json["api"["leagues"]
    for item in data_json: 
        league_id = item["league_id"]
        league_name = item["name"]
        coverage_standings = item["coverage"]["standings"]
        coverage_fixtures_events =    
        item["coverage"]["fixtures"]["events"]
        coverage_fixtures_lineups =    
        item["coverage"]["fixtures"]["lineups"]
        coverage_fixtures_statistics = 
        item["coverage"]["fixtures"]["statistics"]
   coverage_fixtures_players_statistics = item["coverage"]["fixtures"]["players_statistics"]
       coverage_players = item["coverage"]["players"]
       coverage_topScorers = item["coverage"]["topScorers"]
       coverage_predictions = item["coverage"]["predictions"]
       coverage_odds = item["coverage"]["odds"]
       print("leagueName:" league_name, 
      "coverageStandings:" coverage_standings,
     "coverage_fixtures_events:"
      coverage_fixtures_events,
      "coverage_fixtures_lineups:"
      coverage_fixtures_lineups,      
      "coverage_fixtures_statistics:"
       coverage_fixtures_statistics,
      "covage_fixtes_player_statistics:"
      covage_fixres_players_statistics,
      "coverage_players:"
       coverage_players,
      "coverage_topScorers:"
       coverage_topScorers, 
      "coverage_predictions:"
      coverage_predictions, 
      "coverage_odds:"coverage_odds)

1 个答案:

答案 0 :(得分:0)

由于您已将JSON数据作为Python对象加载,因此您应该能够使用常规循环来处理其中的至少一部分。

您似乎在添加下划线以指示JSON对象中的嵌套级别,因此我将在这里进行以下操作:

leagues = open("../forecast/endpoints/leagues.txt", "r")
leagues_json = json.load(leagues)
data_json = leagues_json["api"]["leagues"]

def print_nested_dict(data, *, sep='.', context=''):
    """Print a dict, prefixing all values with their keys,
    and joining nested keys with 'separator'.
    """
    for key, value in data.items():
        if context:
            key = context + sep + key
        if isinstance(value, dict):
            print_nested_dict(value, sep=sep, context=key)
        else:
            print(key, ': ', value, sep='')

print_nested_dict(data_json, sep='_')

如果data_json中有其他您不想打印的数据,最简单的解决方案可能是添加一个列出所需名称的变量,然后在其中添加条件循环,因此只打印那些名称。

def print_nested_dict(data, *, separator='.', context=None, only_print_keys=None):
    ...
    for key, value in data.items():
        if only_print_keys is not None and key not in only_print_keys:
            continue # skip ignored elements
        ...

除非您没有打印很多非常数据,否则它应该可以正常工作。


如果出于某些其他原因确实需要将值存储在变量中,则可以在不污染全局名称空间的情况下将其分配给全局变量。

def print_nested_dict(...):
    ...
        else:
            name = separator.join(contet)
            print(name, ': ', value, sep='')
            globals()[name] = value
    ...