简体   繁体   English

如果某些键具有所需值,如何迭代字典列表并打印字典

[英]How to Iterate over a list of dictionary and print dict if certain key has required value

As you can see below variable y contains a list of dictionaries which contain various details about a few persons, I want to print the dictionary which contains the key named position = 'Account Manager'.正如您在下面看到的变量 y 包含一个字典列表,其中包含有关几个人的各种详细信息,我想打印包含名为 position = 'Account Manager' 的键的字典。

PS: I'm pretty new to Python. PS:我对 Python 很陌生。

y = [{'email': 'hgibson@journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Hannah', 'lastName': 'Gibson', 'position': 'Corporate Flight Attendant'},

 {'email': 'ncucalon@journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Nicole', 'lastName': 'Cucalon', 'position': 'Account Manager'},

 {'email': 'shazamy@journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Sam', 'lastName': 'Hazamy', 'position': 'Maintenance Controller and Invoicing Specialist'}, 

{'email': 'rafaelbajares@journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Rafael', 'lastName': 'Bajares', 'position': 'Gulfstream IV Pilot'}]

for i in y:
    if i.keys.position = 'Account Manager'
    print(i)

Output :输出 :

if i.keys() ='Account Manager':
            ^ SyntaxError: invalid syntax

Your solution seems to be reliant on using a dictionary that is converted to dotted format(like DotDict from Robot framework).您的解决方案似乎依赖于使用转换为点格式的字典(如 Robot 框架中的 DotDict)。 Usually, a dcitionary is read like this y['position'] .通常,字典读作这样y['position']

Anyway, this code should work for your requirement:无论如何,此代码应该可以满足您的要求:

y = [{'email': 'hgibson@journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Hannah', 'lastName': 'Gibson', 'position': 'Corporate Flight Attendant'},
     {'email': 'ncucalon@journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Nicole', 'lastName': 'Cucalon', 'position': 'Account Manager'},
     {'email': 'shazamy@journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Sam', 'lastName': 'Hazamy', 'position': 'Maintenance Controller and Invoicing Specialist'},
     {'email': 'rafaelbajares@journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Rafael', 'lastName': 'Bajares', 'position': 'Gulfstream IV Pilot'}]

for person_dict in y:
    if person_dict.get("position", "") == "Account Manager"
        print person_dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM