0

I am trying to create a for loop to add values to keys in an established dictionary. However, I keep getting the last value instead of all of the values. What I am doing wrong?

My current dictionary looks like:

growth_dict = dict.fromkeys(conc[1:9], '')

growth_dict = {'100 ug/ml': '', '12.5 ug/ml': '', '50 ug/ml': '', 
    '0 ug/ml': '', '6.25 ug/ml': '', '25 ug/ml': '', '3.125 ug/ml': '', 
    '1.5625 ug/ml': ''}

cols_list = numpy.loadtxt(fn, skiprows=1, usecols=range(1,9), unpack=True)

numer = (0.301)*960 #numerator

for i in cols_list:

    N = i[-1]
    No = i[0]
    denom = (math.log(N/No)) #denominator
    g = numer/denom

When I run the program and type "growth_dict," it returns my dictionary with only the last value as the key:

growth_dict = {'100 ug/ml': 131.78785283808514, '12.5 ug/ml': 131.78785283808514, 
    '50 ug/ml': 131.78785283808514, '0 ug/ml': 131.78785283808514, 
    '6.25 ug/ml': 131.78785283808514, '25 ug/ml': 131.78785283808514, 
    '3.125 ug/ml': 131.78785283808514, '1.5625 ug/ml': 131.78785283808514}
1
  • 1
    What output do you get when running this program? What output did you expect? Commented Jun 8, 2012 at 23:22

2 Answers 2

1

You're overwriting the value of the conc[j] dictionary entry each time you do this:

growth_dict[conc[j]] = g

If you want each successive g to be appended to the dictionary entry, try something like:

for j in conc:
    # The first time each key is tested, an empty list will be created
    if not instanceof(growth_dict[conc[j]], list):
        growth_dict[conc[j]] = []
    growth_dict[conc[j]].append(g)
Sign up to request clarification or add additional context in comments.

2 Comments

But I thought that dictionaries don't have the attribute "append?"
@ttdinh: it is a dictionary of lists - each list does have .append()
1

You could also save a lot of effort in loading your data by doing

cols_list = numpy.loadtxt(fn, skiprows=1, usecols=range(1,9), unpack=True)

1 Comment

thank you! this is my first programming class, so i'm still trying to figure out this stuff

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.