Python 3.9.5: A possible bug where a single dictionary assignment is replacing multiple keys

Currently, I am parsing through a .csv file named courses. In this file, each row represents a different course containing an id, a name, and a teacher. My goal is to store this information in a dictionary. For instance:

list_courses = { 
    1: {'id': 1, 'name': 'Biology', 'teacher': 'Mr. D'},
    ... 
 }

As I iterate through the rows using enumerate(file_csv.readlines()), I am carrying out the following steps:

list_courses={}

for idx, row in enumerate(file_csv.readlines()):
                # Skip blank rows.
                if row.isspace(): continue
                
                # If we're using the row, turn it into a list.
                row = row.strip().split(",")

                # Identify header row for keys assignment purposes.
                if not idx: 
                    sheet_item = dict.fromkeys(row)
                    continue
                
                # Assign values found in row to corresponding keys in sheet_item.
                for idx, key in enumerate(list(sheet_item)):
                    sheet_item[key] = int(row[idx].strip()) if key == 'id' or key == 'mark' else row[idx].strip()

                # Add current course to list_courses dictionary.
                print("ADDING COURSE WITH ID {} TO THE DICTIONARY:".format(sheet_item['id']))
                list_courses[sheet_item['id']] = sheet_item
                print("\tADDED: {}".format(sheet_item))
                print("\tDICT : {}".format(list_courses))

After adding each sheet_item to the list_courses dictionary, it prints out the content of the dictionary.

The issue arises when trying to add two courses to list_courses. The expected output should be:

list_courses = { 
    1: {'id': 1, 'name': 'Biology', 'teacher': 'Mr. D'},
    2: {'id': 2, 'name': 'History', 'teacher': 'Mrs. P'}
 }

However, based on my print statements and subsequent errors in the program, the actual result is:

ADDING COURSE WITH ID 1 TO THE DICTIONARY:
        ADDED: {'id': 1, 'name': 'Biology', 'teacher': 'Mr. D'}
        DICT : {1: {'id': 1, 'name': 'Biology', 'teacher': 'Mr. D'}}
ADDING COURSE WITH ID 2 TO THE DICTIONARY:
        ADDED: {'id': 2, 'name': 'History', 'teacher': 'Mrs. P'}
        DICT : {1: {'id': 2, 'name': 'History', 'teacher': 'Mrs. P'}, 2: {'id': 2, 'name': 'History', 'teacher': 'Mrs. P'}}

Although the correct id values are being used for each sheet_item added to courses_list, there seems to be an issue with the key assignment where the second course entry overwrites the values for key 1. This behavior baffles me, and I'm seeking insights on how to resolve it. Any assistance would be greatly appreciated.

Answer №1

The dictionary you're using is the same for both the header and all rows, causing key assignments to overwrite previous values. To fix this issue, store the keys in a list and create a new sheet_item before the for loop:

list_courses={}
keys = None # Indicate that this is defined

for idx, row in enumerate(file_csv.readlines()):
                if row.isspace(): continue
                
                row = row.strip().split(",")

                if not idx: 
                    keys = row
                    continue
                
                sheet_item = {}
                
                for idx, key in enumerate(keys):
                    sheet_item[key] = int(row[idx].strip()) if key == 'id' or key == 'mark' else row[idx].strip()

                print("ADDING COURSE WITH ID {} TO THE DICTIONARY:".format(sheet_item['id']))
                list_courses[sheet_item['id']] = sheet_item
                print("\tADDED: {}".format(sheet_item))
                print("\tDICT : {}".format(list_courses))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Custom __getattr__ implementation causing _repr_html_ to not display

At the moment, I am in the process of incorporating _repr_html_ into a python class (docs). This particular class acts as a readonly interface for navigating an object similar to JSON using attribute notation. It is based on example 19-5 from Fluent Pytho ...

Is there a way to utilize in Python to have the text printed on the same line?

Could someone provide a detailed explanation of how the '\r' character functions in Python? I'm curious why the code below isn't displaying any output on the screen. #!/usr/bin/python from time import sleep for x in range(10000) ...

Function to reverse elements in Python

Define a function called is_reverse that takes two parameters, which are arrays of integers of the same size. The function should return true if one array is the reverse of the other (meaning they have the same elements but in reverse order). Here's ...

Executing Selenium script using Python to download and change the name of a file

I've been facing a challenge while using selenium to download and rename files (around 60 per page). Here's what I've attempted: 1. First, I tried using the solution provided by supputuri to go through the chrome://downloads download manage ...

Mastering the art of list comprehension in Python: avoiding the common pitfall of getting stuck with a list of booleans

My goal is to eliminate periods, commas, single and double quotes from the end of each string within a list. Each string is part of a larger list of strings. string_list= ["cars." , "red" , "orange," , "man'" , "thus:"] desired_output --->["cars" ...

What is the best way to incorporate various variables into the heading of my plot design?

I need the title to display as: "Target Electron Temperature =Te_t [ev] Target Density=n_t [m^-3]" The values of Te_t and n_t represent the input variables. While I can successfully generate the title with one variable, I am having trouble including bot ...

Or Tools to solve Nurse Scheduling Problem, incorporating varying shift lengths for specific days

I'm currently tweaking the code provided in a tutorial (link available here) and I am aiming to incorporate shifts of different lengths for specific days. For instance, I wish for Friday/Day 4 to have only 2 shifts. However, my code consistently resul ...

Unable to assign a default value of an object variable in an object method - Python

Using Windows 10, x64, and Python 2.7.8. I'm trying to implement the code below: class TrabGraph: def __init__(self): self.radius = 1.0 def circle(self, rad=self.radius): print(rad) test = TrabGraph() test.circ ...

Authentication of POST API requests

As a newcomer to Python, I am eager to retrieve data from my private account on the cryptocurrency market bitbay.net. You can find the API description here: Below is my Python 3.5 code snippet: import requests import json import hashlib import time has ...

Inverting Django translations

Can you retrieve msgid from msgstr? Let's assume we have msgid "Table" msgstr "Tisch" If the active language is German, is there a function that can execute inverse_ugettext('Tisch') -> Table? ...

Improper transformation of raw RGB depth image into grayscale

Working with a Python simulation that includes a depth sensor and C++ visualization has been quite challenging for me. The sensor provides an image that needs to be converted to grayscale. https://i.stack.imgur.com/Dmoqm.png To achieve the conversion, I ...

Retrieving information from a text file using Python 3

I have created a script that saves players' names along with their scores. My goal is to retrieve this data back into Python for the purpose of organizing it into a table within a user interface. I believe there must be a straightforward solution, b ...

Is there a way to delay the running of Celery tasks?

There is a dilemma I'm facing with my small script that enqueues tasks for processing. It performs numerous database queries to obtain the items that need to be enqueued. The problem arises when the celery workers immediately start picking up the task ...

Combine and add elements from an array based on multiple conditions

Hey everyone! I'm curious about how to concatenate array elements under specific conditions. Let's say I have an array like this: X=[[123,Q],[456,R],...,[789,S]] and another array like this: Y=[[123,-0.22,0.99],[456,-0.442,0.99],...,[789,-1. ...

Preventing program continuation when KeyboardInterrupt occurs with multiprocessing.Pool in Python

Similar Question: Handling Keyboard Interrupts in Python's Multiprocessing Pool The multiprocessing module in Python includes a feature known as Pool, which can be found at http://docs.python.org/library/multiprocessing.html#module-multiprocessin ...

When Selenium is not in headless mode, it cannot capture a screenshot of the entire website

Disclaimer: Although there is a similar question already out there, none of the answers provided worked for a headless browser. Therefore, I have decided to create a more detailed version addressing this specific issue (the original question I referred to ...

Steps for extracting HTML content from a beautiful soup object

My current situation involves a bs4 object listing: >>> listing <div class="listingHeader"> <h2> .... >>> type(listing) <class 'bs4.element.Tag'> I am aiming to retrieve the raw html as a string. Initially, ...

Issue discovered: pytest configuration in pytest.ini is not being recognized when pytest.ini is located inside the "tests" subdirectory instead of the main

pytest is giving a warning about an unrecognized custom mark when running my test suite, even though I believe I have registered it correctly according to the pytest documentation (refer to this link). The structure of my Python project is as follows: my_ ...

Tips for creating a Scrapy spider to extract .CSS information from a table

Currently, I am utilizing Python.org version 2.7 64-bit on Windows Vista 64-bit for building a recursive web scraper using Scrapy. Below is the snippet of code that successfully extracts data from a table on a specific page: rows = sel.xpath('//table ...

How to extract and display data in Python using JSON parsing techniques

In search of the right syntax for extracting and displaying specific JSON data using Python Check out this example JSON file: Sample JSON Response from Play Information: { "id": 111, "age": 22, "Hobby": [ { "List": 1, "Sev": "medium", "name": "play 1" ...