Created
February 15, 2026 08:28
-
-
Save curious3/be54cd06b6bbd3ed85e8f423ed7b0022 to your computer and use it in GitHub Desktop.
merge_dict_with_csv.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import json | |
| import csv | |
| def merge_dict_with_csv(dict_a, csv_file_path): | |
| """ | |
| Replace keys in dictA with values from CSV and add any new keys from CSV to dictA. | |
| Args: | |
| dict_a: Dictionary to be updated | |
| csv_file_path: Path to CSV file with keys in column 1 and values in column 2 | |
| Returns: | |
| Updated dictionary | |
| """ | |
| # Read the CSV file and create a mapping | |
| csv_mapping = {} | |
| with open(csv_file_path, 'r', encoding='utf-8') as csvfile: | |
| csv_reader = csv.reader(csvfile) | |
| for row in csv_reader: | |
| if len(row) >= 2: | |
| key = row[0] | |
| value = row[1] | |
| csv_mapping[key] = value | |
| # Create a new dictionary to store results | |
| result_dict = {} | |
| # Process existing keys in dictA | |
| for key, value in dict_a.items(): | |
| # If this key exists in CSV mapping, use the CSV value as the new key | |
| if key in csv_mapping: | |
| new_key = csv_mapping[key] | |
| result_dict[new_key] = value | |
| else: | |
| # Keep the original key | |
| result_dict[key] = value | |
| # Add any new keys from CSV that weren't in dictA | |
| for csv_key, csv_value in csv_mapping.items(): | |
| # If the CSV value (which becomes the new key) isn't already in result | |
| if csv_value not in result_dict: | |
| # Add it with None or empty value (you can customize this) | |
| result_dict[csv_value] = None | |
| return result_dict | |
| # Example usage | |
| if __name__ == "__main__": | |
| # Example dictionary | |
| dictA = { | |
| "name": "John Doe", | |
| "age": 30, | |
| "city": "New York", | |
| "email": "john@example.com" | |
| } | |
| # Example: Create a sample CSV file | |
| sample_csv = "mapping.csv" | |
| with open(sample_csv, 'w', newline='', encoding='utf-8') as f: | |
| writer = csv.writer(f) | |
| writer.writerow(["name", "full_name"]) | |
| writer.writerow(["age", "years_old"]) | |
| writer.writerow(["country", "nation"]) # New key not in dictA | |
| print("Original dictionary:") | |
| print(json.dumps(dictA, indent=2)) | |
| print("\nCSV mapping:") | |
| with open(sample_csv, 'r') as f: | |
| print(f.read()) | |
| # Merge | |
| result = merge_dict_with_csv(dictA, sample_csv) | |
| print("\nUpdated dictionary:") | |
| print(json.dumps(result, indent=2)) | |
| # Save result to JSON file | |
| with open('result.json', 'w', encoding='utf-8') as f: | |
| json.dump(result, f, indent=2) | |
| print("\nResult saved to result.json") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment