Python读取CSV至全局字典并为字典添加数值的问题
Got it, let's tackle these two problems step by step—they're pretty straightforward once you break them down!
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.
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

