0

i'm trying to do a 'for' loop in python, but my values keeps getting replaced. How can i write the code below in a way where i can keep a record of each iteration?

Should i be using a list[] instead of dict{} for "position"..?

for share in sharesOwned:   
        #how to iterate through the look up symbol?
        sharesNow=lookup(share['symbol'])

        position={
            'name':sharesNow['name'],
            'pricey': sharesNow['price'],
            'symbol': sharesNow['symbol']
            }

I also tried this, but it does not work..

for share in sharesOwned:   
        #how to iterate through the look up symbol?
        sharesNow=lookup(share['symbol'])

        position[share]=[
            'name':sharesNow['name'],
            'pricey': sharesNow['price'],
            'symbol': sharesNow['symbol']
            ]

It returns this

TypeError: list indices must be integers, not dict

How do it put insert these information into a list i can access/call?


Original question is here but i'm really confuse, so I thought it'd solve it part by part.

1 Answer 1

1

In a dictionary the indices use strings, whereas lists are indexed using integers beginning with 0. The error:

TypeError: list indices must be integers, not dict

is because you are using string as indices instead of integers. If you want to use strings like "name" to get values from the array you should use a dictionary.

Your values will get replaced for each iteration because every time the loop iterates you are overwriting the previous values. You can create an array or dictionary outside the loop and store the values. Remember you need to change the indice of the dictionary / list for each iteration of the loop or you will just be overwriting the same index each time.

Using a for loop on a dictionary will assign the keys to the variable.

Using a for loop on a list will assign the values to the variable.

Using range(len()) will give you the indices (0 to length of list / dictionary).

fruits = {"red": "apple", "green": "grape", "yellow": "banana"}

for colour in fruits:
    print (colour)
// Prints keys of dictionary: "red", "green", "yellow"

animals = ["cat", "dog", "rabbit"]

for animal in animals:
    print (animal)
// Prints values in animals: "cat", "dog", "rabbit"

for index in range(len(animals)):
    print (index)
// Prints indices of fruits: 0, 1, 2
2
  • But isn't share now a number when we are iterating it just like how i in int i= 0; i < sharesOwned; i++, does python automatically declare shares as a number 0?
    – nvs0000
    Commented May 20, 2017 at 19:14
  • I have added information to my answer. Using a for loop on a dictionary gives you the keys, using a for loop on a list will give you values. You can use the range in your for loop to get indexes. Commented May 20, 2017 at 21:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .