如何为CSV文件仅前两行设预定义键,后两行用CSV内键?
Adjusting Your CSV-to-Dictionary Code for Predefined Keys
Got it, let's tweak your code to produce exactly the dictionary format you're aiming for. Here's the modified version that uses predefined keys for the first two rows and the CSV's own keys for the rest:
import csv import pprint portfolio = {} def loadPortfolio(fname): try: # Define our predefined keys for the first two rows predefined_keys = ['Date', 'Cash'] with open(fname, "rt") as f: reader = csv.reader(f) # Iterate with index to track which row we're processing for idx, row in enumerate(reader): # For first two rows, use predefined keys if idx < len(predefined_keys): key = predefined_keys[idx] # Assuming each row has a value in the second position (adjust if needed) value = row[1] # For all other rows, use the key from the CSV else: key = row[0] value = row[1] # Add to our portfolio dict portfolio[key] = value pprint.pprint(portfolio) except FileNotFoundError: print(f"Error: File {fname} not found.") except Exception as e: print(f"An error occurred: {e}") # Example usage: # loadPortfolio('your_file.csv')
Key Changes Explained:
- Enumerate Rows: We use
enumerate()to keep track of which row we're on, so we can apply the predefined keys only to the first two rows. - Predefined Keys List: The
predefined_keyslist holds the exact keys you want ('Date' and 'Cash') for the first two entries. - Value Handling: Changed
row[1:]torow[1]because your target dictionary uses string values (like '20000') instead of lists. - Error Handling: Added basic error handling for missing files and other exceptions to make the code more robust.
Assumed CSV Structure:
This code works with a CSV where each row is a key-value pair. For example, your CSV might look like this:
OriginalDateKey,###### OriginalCashKey,20000 SKY,5 EZJ,8
Running the code on this CSV will produce your desired output:
{'Cash': '20000', 'Date': '######', 'EZJ': '8', 'SKY': '5'}
If your first two rows don't have an original key (they're just the values themselves), we can adjust the code to take row[0] as the value for those rows instead—just let me know if that's your case!
内容的提问来源于stack exchange,提问作者Bhaiyattt
相关产品推荐
相关产品推荐

