I am trying to use lists as dictionary values. I am running a loop that creates a new list each time and then assigns it to a specific key. The iteration works the first time. However, when I clear the temporary list and populate the list with new information and assign the list to the next key, the keys remain unique but the previous dictionary values all become the current list values. I believe this is somehow a memory pointer issue, but how can I make this work? Thanks.
Using Lists as Dictionary Values
Using Lists as Dictionary Values
|
Apr-19-2024, 08:57 PM
Can you post the code you are using?
I welcome all feedback.
The only dumb question, is one that doesn't get asked. My Github How to post code using bbtags Download my project scripts
Apr-19-2024, 11:23 PM
Sounds like you are reusing the list object instead of creating a new list. This creates a dictionary with multiple entries, but only one value.
a = [1, 2, 3, 4] b = {'A': a, 'B': a, 'C': a} b['C'].append(5) print(b) It is pretty obvious that all entries in dictionary "b" have the same list value "a". Appending 5 to b['C'] appends 5 to the list "a". Since all entries in the dictionary reference "a", it looks like we changed all the entries in the dictionary.You should not be doing this: Quote:However, when I clear the temporary list and populate the list with new informationInstead of reusing a temporary list you should create a new list for each entry. Like this. a = [1, 2, 3, 4] b = {} for key in "ABC": b[key] = [1, 2, 3, 4] # make a new list each time b['C'].append(5) print(b) Each list in the dictionary is now a different list object. It may contain the same values, but the list object, the container for those values is different. Changing the values in one entry doesn't do anything to the other entries, because changing a list doesn't change other lists.
Apr-20-2024, 03:49 AM
Show your code - minimal reproducible example
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link Create MCV example Debug small programs
Apr-20-2024, 02:23 PM
(This post was last modified: Apr-20-2024, 03:28 PM by deanhystad.)
Here is the code. The data comes from a file with lines of 15 pieces of text separated by a space. The first piece of text in each line will become the 'key' and a temporary list is made of other pieces of text and that list is to be the 'value' for the respective 'key'. Each time through, the new key is added, but, after all the data is processed, every key ends up with the same list as the value.
for new_line in data: new_line = new_line.strip() print(f'\n{new_line} : Line Length = {len(new_line)}') # read in the rd info / split on whitespace rd_info = list(new_line.split()) print(rd_info) # create dictionary temp_list.clear() rd_name = rd_info[0] rd_age = int(rd_info[3]) rd_yr = int(rd_info[6]) rd_yr_left = rd_yr rd_wt = int(rd_info[13]) rd_wt_left = rd_wt rd_fg = 0 rd_stp = 0 temp_list.append(','.join([str(rd_age), str(rd_yr), str(rd_yr_left), str(rd_wt), str(rd_wt_left), str(rd_fg), str(rd_stp)])) print(f'Temp List: {temp_list}') rd_dict[rd_name] = temp_list print(rd_dict) deanhystad write Apr-20-2024, 03:28 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Apr-20-2024, 03:46 PM
Don't reuse temp_list. Instead of clearing the list and appending the string, create a new list like this:
temp_list = [','.join([str(rd_age), str(rd_yr), str(rd_yr_left), str(rd_wt), str(rd_wt_left), str(rd_fg), str(rd_stp)])]Why are making lists that only have one value?
Apr-20-2024, 09:55 PM
The last part of the code assigns the list to a unique key in the dictionary. I was hoping to end up with a large dictionary of unique keys and a different list as the value for each key.
Apr-20-2024, 11:44 PM
(This post was last modified: Apr-20-2024, 11:44 PM by deanhystad.)
(Apr-20-2024, 09:55 PM)bfallert Wrote: The last part of the code assigns the list to a unique key in the dictionary. I was hoping to end up with a large dictionary of unique keys and a different list as the value for each key.I still don't understand why you are using lists. This makes one string. rd_str = ','.join([str(rd_age), str(rd_yr), str(rd_yr_left), str(rd_wt), str(rd_wt_left), str(rd_fg), str(rd_stp)])This puts that one string in a list temp_list.clear() temp_list.append(rd_str)You are creating a dictionary of lists, but each list contains a single string, not a list of values, If you want the lists to be a list of values, don't join all the values into a string. Do this: for new_line in data: rd_info = list(new_line.split()) rd_name = rd_info[0] rd_age = int(rd_info[3]) rd_yr = int(rd_info[6]) rd_yr_left = rd_yr rd_wt = int(rd_info[13]) rd_wt_left = rd_wt rd_fg = 0 rd_stp = 0 rd_dict[rd_name] = [rd_age, rd_r, rd_r_left, rd_wd, rd_wt_left, rd_fg, rd_stp] print(rd_dict)Now rd_dict is a dictionary of lists, each list containing the values from a line in data.
Apr-21-2024, 06:55 AM
If you had provided some data that would have been nicer!
You can make an empty dictionary like this: mydict = {j:'' for j in range(25)}j is the key and the value is an empty string. Loop through the keys and replace the empty string with anything you like: for key in mydict.keys(): mydict[key] = 'value' + str(key + 1)Like I said, if you had provided some data, that would have been better! import uuid from random import choice, randint from string import ascii_lowercase # make a random string for rd_info[0] def randomString(): random_string = ''.join([choice(ascii_lowercase) for i in range(4)]) return random_string # make a random integer for rd_info[3], rd_info[6], rd_info[13] def randomInt(): random_integer = randint(1989, 2022) return random_integer # make some data because you did not provide any data # make a list of lists data = [[randomString(), randomInt(), randomInt(), randomInt(), 0, 0] for i in range(25)] # make some fairly unique keys: keys = [str(uuid.uuid4()) for i in range(25)] # make a dictionary of empty strings mydict = {key:'' for key in keys} # now populate mydict with your data # you did not provide a sample of your data so I can't use your data i = 0 for key in mydict.keys(): # put a data list in mydict as value mydict[key] = data[i] i +=1 |
|
Users browsing this thread: 1 Guest(s)