You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取CSV至全局字典并为字典添加数值的问题

Got it, let's tackle these two problems step by step—they're pretty straightforward once you break them down!

1. Load Player Names from CSV First Column into a Global Dictionary

The built-in csv module in Python is the cleanest way to handle this, no messy string splitting required. Here's a complete example, with comments to explain each step:

import csv

# Define your global dictionary at the top level
player_rank_map = {}

def load_players_from_csv(csv_file_path):
    global player_rank_map  # Declare we're using the global dictionary
    with open(csv_file_path, mode='r', newline='', encoding='utf-8') as csv_file:
        csv_reader = csv.reader(csv_file)
        
        # Skip the header row if your CSV has one (e.g., "Player Name" as the first column label)
        next(csv_reader)
        
        for row in csv_reader:
            if row:  # Skip empty rows to avoid errors
                player_name = row[0].strip()  # Remove extra spaces around the name
                player_rank_map[player_name] = None  # Initialize with None, we'll fill ranks later

# Replace with your actual CSV file path
load_players_from_csv("game_players.csv")

A few quick notes:

  • If your CSV doesn't have a header row, just remove the next(csv_reader) line.
  • Using .strip() prevents matching issues from accidental spaces in player names (like " Alice " vs "Alice").
  • If your CSV has duplicate names, the last occurrence will overwrite the earlier one in the dictionary. If you need to handle duplicates, you could adjust the dict to store lists instead of single values.
2. Update the Dictionary with Player Ranks from Your Sorted List

Assuming your pre-sorted list is in order from 1st place to last, we can use enumerate() with a start value of 1 to map each player directly to their rank:

# Example sorted list (replace with your actual ranked player list)
ranked_players = ["Luna", "Kai", "Mia", "Jasper"]

def update_player_ranks():
    global player_rank_map
    for rank, player_name in enumerate(ranked_players, start=1):
        if player_name in player_rank_map:
            player_rank_map[player_name] = rank
        else:
            # Optional: Handle players in the ranked list but not in the CSV
            print(f"Warning: {player_name} wasn't found in the CSV data—skipping rank assignment.")

# Run the update
update_player_ranks()

# Check the result (optional)
print(player_rank_map)

This will loop through your ranked list, find each player in the global dictionary, and set their value to their corresponding rank. If a player in the ranked list isn't in the CSV, it'll print a warning (you can remove this if you don't need it).

内容的提问来源于stack exchange,提问作者Sean

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:53:18