I come from javascript and I would like to know how I can go through that array that in python is known as list.
"dispatches_types": [
{
"status_id": 2
},
{
"status_id": 1
},
{
"status_id": 1
},
{
"status_id": 1
},
{
"status_id": 2
}
]
The problem I have is that I want to add a counter that increases when status_id
it is 1 but this is dynamic since sometimes it can bring that status and sometimes not. Sometimes it can even bring up the empty list.
So far I am trying this way:
cont = 0
if len(dispatch_types) > 0:
for status1 in dispatch_types:
if 1 in status1:
cont +=1
else:
cont = 0
There are several forms that are more "phytonic", or at least that take better advantage of the language tools, also collaterally tend to be easier to read. First of all, your example is a dictionary whose key
"dispatches_types"
contains a list of other dictionaries. Something like this:What you are looking for is to determine how many
status_id == 1
are in the mentioned list. One way is as follows:[1 for e in d["dispatches_types"] if e["status_id"]==1]
we use a list comprehension to construct a new list with a value1
for every time we havestatus_id == 1
sum()
we simply add the list.status_id == 1
existent ones, in both cases it will return0
Also. you may find it interesting, the use of the class
Counter()
He
Counter
will return you from the liste["status_id"] for e in d["dispatches_types"]
. a dictionary-like object, with the occurrences for eachstatus_id
I solved it this way but I still have doubts: