python使用两个准则在另一个文件中查找字典键

2024-04-20 10:33:10 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的代码结束后,我有一本这样的字典:

{'"WS1"': 1475.9778073075058, '"BRO"': 1554.1437268304624, '"CHA"': 1552.228925324831}

我要做的是在一个单独的文件中找到每个键,团队.txt,格式如下:

1901,'BRO','LAD'
1901,'CHA','CHW'
1901,'WS1','MIN'

使用年份(1901年)和团队(字典中每个项目的键),我想创建一个新字典,其中键位于团队.txt如果年份和团队都匹配,那么值就是第一个字典中团队的值。你知道吗

我想,如果我创建一个函数来“查找”年份和团队,并返回“franch”,然后将该函数应用于字典中的每个键,这将是最简单的。这是我到目前为止得到的,但它给了我一个KeyError

def franch(year, team_str):
  team_str = str(team_str)
  with open('teams.txt') as imp_file:
    teams = imp_file.readlines()
  for team in teams:
    (yearID, teamID, franchID) = team.split(',')
    yearID = int(yearID)
    if yearID == year:
      if teamID == team_str:
        break
  franchID = franchID[1:4]
  return franchID

在另一个有字典的函数中,我想把这个函数应用到:

  franch_teams={}
  for team in teams:
    team = team.replace('"', "'")
    franch_teams[franch(year, team)] = teams[team]

我正在努力实现的理想结果如下所示:

{'"MIN"': 1475.9778073075058, '"LAD"': 1554.1437268304624, '"CHW"': 1552.228925324831}

谢谢!你知道吗


Tags: 函数txt字典团队yearteambro年份
2条回答

这个代码适合你的需要吗?你知道吗

我正在额外检查是否相等,因为在代码的不同部分中有不同的字符串符号。你知道吗

def almost_equals(one, two):
    one = one.replace('"', '').replace("'", "")
    two = two.replace('"', '').replace("'", "")
    return one == two

def create_data(year, data, text_content):
    """ This function returns new dictionary. """
    content = [line.split(',') for line in text_content.split('\n')]
    res = {}

    for key in data.keys():
        for one_list in content:
            if year == one_list[0] and almost_equals(key, one_list[1]):
                res[one_list[2]] = data[key]

    return res


teams_txt = """1901,'BRO','LAD'
1901,'CHA','CHW'
1901,'WS1','MIN'"""

year = '1901' 
data = { '"WS1"': 1475.9778073075058, '"BRO"': 1554.1437268304624, '"CHA"': 1552.228925324831 }
result = create_data(year, data, teams_txt)

以及输出:

{"'CHW'": 1552.228925324831, "'LAD'": 1554.1437268304624, "'MIN'": 1475.9778073075058}

更新:

要读取文本文件,请使用此函数:

def read_text_file(filename):
    with open(filename) as file_object:
        result = file_object.read()

    return result

teams_txt = read_text_file('teams.txt')

您可以尝试以下方法:

#!/usr/bin/env python

def clean(_str):
    return _str.strip('"').strip("'")

first = {'"WS1"': 1475.9778073075058, '"BRO"': 1554.1437268304624, '"CHA"': 1552.228925324831}

clean_first = dict()
second = dict()

for k,v in first.items():
    clean_first[clean(k)] = v

with open("teams.txt", "r") as _file:
    lines = _file.readlines()
    for line in lines:
        _,old,new = line.split(",")
        second[new.strip()] = clean_first[clean(old)]

print second

给出了预期的:

{"'CHW'": 1552.228925324831, "'LAD'": 1554.1437268304624, "'MIN'": 1475.9778073075058}

相关问题 更多 >