首页 > 解决方案 > Python:根据多个字典中的值生成新名称

问题描述

对 python 来说相对较新,如果问题/脚本冗长且含糊不清,我们深表歉意。下面的脚本返回搜索到的球队名称的键和值(例如:2,夏洛特黄蜂队);但是,我也希望它返回它所在的联赛名称。如'nfl'、'nba'、'mlb';根据它所在的字典(例如:2,夏洛特黄蜂队,nba)。已经为此工作了一段时间,但找不到动态解决方案。我在这里先向您的帮助表示感谢!

NFL_Teams = {1: "Arizona Cardinals", 2: "Atlanta Falcons", 3: "Baltimore Ravens"}
NBA_Teams = {1:'Washington Wizards', 2:'Charlotte Hornets', 3: 'Atlanta Hawks'}
MLB_Teams = {1: 'Los Angeles Dogers', 2: 'Cincinnati Reds', 3: 'Toronto Blue Jays'}    

def Standings(reply):
    def dictionary_search(name, dictionary):
        for key, value in dictionary.items():
            if value == name:
                return True # Boolean to show if team name is in merged dictionaries. 
            if key == name:
                pass # Used as a throw-away variable

    for single_dictionary in (NFL_Teams, NBA_Teams, MLB_Teams):
        if dictionary_search(reply, single_dictionary):
            for key, value in single_dictionary.items():
                if reply == value:
                    print(key, value)
            break
    else:
        print('Please Try Again')

Standings('Charlotte Hornets')

标签: pythonpython-3.xloopsdictionaryfor-loop

解决方案


用作键的数字重要吗?反过来将它们读入字典是否有意义?- 然后你可以使用一个try except KeyError语句。这对于非常大的字典可能更可取(尽管对于联盟中的球队来说情况并非如此)。这也可能是一种更面向对象的思维方式:球队名称是对象标识符,而(我假设数字是当前联赛排名?)联赛排名是一个属性(并且是一个可变属性)。例如(改编 Aaron_ab 的回答)

teams = {'NFL': {"Arizona Cardinals":1, "Atlanta Falcons":2, "Baltimore Ravens":3},
     'NBA': {'Washington Wizards':1, 'Charlotte Hornets':2, 'Atlanta Hawks':3},
     'MLB': {'Los Angeles Dogers':1, 'Cincinnati Reds':2, 'Toronto Blue Jays':3}}

def standings(team):
    for league, teams_dict in teams.items():
        try:
            teams_dict[team]
            print(teams_dict[team], team)
            print(league)
            break
        except KeyError:
            continue   

或者,删除数字并拥有一个列表字典(其中列表的顺序是当前的联赛顺序):

import numpy as np

teams = {'NFL': ["Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens"],
     'NBA': ['Washington Wizards', 'Charlotte Hornets', 'Atlanta Hawks'],
     'MLB': ['Los Angeles Dogers', 'Cincinnati Reds', 'Toronto Blue Jays']}

def standings(team):
    for league, teams_list in teams.items():
        if team in teams_list:
            print(team, np.where(np.array(teams_list)==team)[0])
            print(league)

推荐阅读