[英]Loop through list in dictionary with dictionary values
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. 希望我不会让您感到困惑;),如何获得结果列表并遍历列表中的每个字典,以比较它们之间的id与if语句。
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
: 在dic
获取值:
for dic in resultList:
for key,value in dic.iteritems():
# use key and value
To access the id
key, use: 要访问id
密钥,请使用:
for dic in resultList:
if dic['id'] == somevalue:
# do_something
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. 如果要“ 循环遍历列表中的每个字典,以使用if语句比较它们之间的id
” ,则这是一种方法。 Example if
statement below: 下面的if
语句示例:
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. BTW:你必须转换toto
和cool
到string
,除非它们是variables
,你在你的代码已经宣布了。
Not sure what you mean by 'compare the id between them with an if statement'. 不确定“用if语句比较它们之间的ID”是什么意思。 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'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.