Home > database >  Unable to store values in an array from for loop in python
Unable to store values in an array from for loop in python

Time:10-13

First I tried directly storing values from a list having the name 'data' in an array variable 'c' using loop but 'none' got printed

for i in data:
    print(i['name'])
    c=i['name']

Here print(i['name']) perfectly worked and output appeared

This is the working ouput enter image description here

Then I printed c in order to print the values generated using loop. The ouput came as none.

print(c)

enter image description here

Then I tried another way by storing the values and making the array iterable at the same time using for loop. An error occurred which I was unable to resolve.

for i in data:
    b[c]=i['name']
    c=c 1

The error apeared is as follow- enter image description here

I have tried two ways, if there is any other way please help me out as I am new to python.

CodePudding user response:

Not entirely sure if this is a legit question but, add

b = []

above your first line of code. As the error is saying that you have not (and correctly so) defined the list to append.

I personally would use list comp here

b = [obj['name'] for obj in data]

where obj is i as you have defined it.

CodePudding user response:

It looks like the variable 'data' is a dictionary. If you want to add each name from that dictionary to a list:

# create a new list variable
names = []

for i in data:
    name = i['name']
    print(name)
    # add the name to the list
    names.append(name)


# output the new list
print(names)

CodePudding user response:

Assuming your data object here is a list like [{"name": "Mr. Green", ...}, {"name": "Mr. Blue", ...}].

If your goal is to end up with c == ["Mr. Green", "Mr. Blue"], then you're looking for something like:

c = []
for i in data:
    c.append(i['name'])

print(c)

or you can accomplish tasks like these using list comprehensions like:

c = [i['name'] for i in data]
print(c)

The first code example you posted is iterating through the items in data and reassigning the value of c to each item's name key - not adding them to a list("array"). Without knowing more about the code you ran to produce the screenshot and/or the contents of data, it's hard to say why you're seeing print(c) produce None. I'd guess the last item in data is something like {"name": None, ...} which if it's coming from JSON is possible if the value is null. Small note: I'd generally use .get("name") here instead so that your program doesn't blow up if an item is missing a "name" key entirely.

For your second code example, the error is different but I think falls along a similar logical fallacy which is that lists in python function differently from primitives(things like numbers and strings). For the interpreter to know that b or c are supposed to be lists("arrays"), they need to be instantiated differently and they have their own set of syntax/methods for mutation. For example, like arrays in other languages, lists are indexed by position so doing b[c] = <something> will only work if c is an integer. So something similar to your second example that would also produce a list of names like my above would be:

b = [None] * len(data)
c = 0
for i in data:
    b[c]=i['name']
    c=c 1

Note that if you only initialize b = [], you get an IndexError: list assignment index out of range on the initial assignment of b[0] = "some name" because the list is of size 0.

  • Related