Python Forum
Using Lists as Dictionary Values
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using Lists as Dictionary Values
#1
Question 
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.
Reply
#2
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


Reply
#3
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)
Output:
{'A': [1, 2, 3, 4, 5], 'B': [1, 2, 3, 4, 5], 'C': [1, 2, 3, 4, 5]}
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 information
Instead 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)
Output:
{'A': [1, 2, 3, 4], 'B': [1, 2, 3, 4], 'C': [1, 2, 3, 4, 5]}
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.
Reply
#4
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

Reply
#5
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.
Reply
#6
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?
Reply
#7
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.
Reply
#8
(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.
bfallert likes this post
Reply
#9
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  need to compare 2 values in a nested dictionary jss 2 893 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Printing specific values out from a dictionary mcoliver88 6 1,463 Apr-12-2023, 08:10 PM
Last Post: deanhystad
  user input values into list of lists tauros73 3 1,088 Dec-29-2022, 05:54 PM
Last Post: deanhystad
Question How to print each possible permutation in a dictionary that has arrays as values? noahverner1995 2 1,773 Dec-27-2021, 03:43 AM
Last Post: noahverner1995
  Getting values from a dictionary brunolelli 5 3,635 Mar-31-2021, 11:57 PM
Last Post: snippsat
  Python dictionary with values as list to CSV Sritej26 4 3,064 Mar-27-2021, 05:53 PM
Last Post: Sritej26
  Conceptualizing modulus. How to compare & communicate with values in a Dictionary Kaanyrvhok 7 4,055 Mar-15-2021, 05:43 PM
Last Post: Kaanyrvhok
  Adding keys and values to a dictionary giladal 3 2,531 Nov-19-2020, 04:58 PM
Last Post: deanhystad
  In this dictionary all the values end up the same. How? Pedroski55 2 1,950 Oct-29-2020, 12:32 AM
Last Post: Pedroski55
  Counting the values ​​in the dictionary Inkanus 7 3,739 Oct-26-2020, 01:28 PM
Last Post: Inkanus

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020