Reputation:
Given a dictionary as such
grouped_data = {"results":[{"id": 101, "name": toto}, {"id": 102, "name": cool}] }
It's a dict that has a list in which it has dictionaries
Hope I'm not confusing you ;), how can I get the results list and loop through each dictionary inside the list to compare the id between them with an if statement.
Upvotes: 0
Views: 2035
Reputation: 2840
Not sure what you mean by 'compare the id between them with an if statement'. Many ways to interpret it but here is something that you might use:
print (x for x in grouped_data['results'] if x['id'] > 101).next()
Output:
{'id': 102, 'name': 'cool'}
Upvotes: 0
Reputation: 11134
To get the list:
resultList = grouped_data["results"]
Iterate through the list to get the dictionaries:
for dic in resultList:
# use dic
To get values inside dic
:
for dic in resultList:
for key,value in dic.iteritems():
# use key and value
To access the id
key, use:
for dic in resultList:
if dic['id'] == somevalue:
# do_something
Upvotes: 2
Reputation: 6589
If you want to "loop through each dictionary inside the list to compare the id
between them with an if statement", this is one way to do it.
Example if
statement below:
for i in grouped_data["results"]:
if i['id'] > 101:
print (i)
Output:
{'id': 102, 'name': 'cool'}
BTW: You have to convert toto
and cool
to string
unless they are variables
which you have declared in your code already.
Upvotes: 1