简体   繁体   English

Python:从字典中提取条件信息

[英]Python: Extracting Conditional Information from a Dictionary

I am using Python 3.5 to iterate over a dictionary. 我正在使用Python 3.5遍历字典。 I am trying to check for certain conditions in the dataset below, and to return a message if the condition is either untrue or if there is no data to evaluate the condition. 我正在尝试检查下面的数据集中的某些条件,并返回一条消息,如果条件不正确或没有数据可以评估该条件。

data = {
            "Barry": {
                "Title": "CTO", 
                "YOB": 1980, 
                "Direct_Reports": ["Hannah"],
                "Awards": ["Tech Innovator", "Best CTO"],
                "Salary": 1200000
            }, 
            "Joe": {
                "Title": "Data Scientist", 
                "YOB": 1981,
                "Salary": 200000
            },
            "Bill": { 
                "Title": "Senior Software Engineer", 
                "YOB": 1993, 
                "Direct_Reports": [],
                "Awards": ["Employee of the Month"]
            }, 
            "Jose": { 
                "Job": "Full Stack Engineer", 
                "YOB": 1996, 
                "Direct_Reports": ["John", "Hannah"]
            },
        }

For example, I can iterate over the dictionary to print the name of the people listed: 例如,我可以遍历字典以打印列出的人员的姓名:

for name in data.keys():
    print (name)

or 要么

for name in data.items():
        print (name[1]['YOB'])

to get everyone's Year of Birth. 获得每个人的生日。

However, if I run 但是,如果我跑步

for name in data.items():
    print (name[1]["Salary"])

it gives me an error, since the data doesn't capture everyone's Salary, just as not everyone has received an award. 它给了我一个错误,因为数据无法捕获每个人的薪水,就像不是每个人都获得了奖励一样。 How could I go about doing this, or extracting salaries only for people above a certain threshold, for example, 500000? 我该如何去做,或者只为某个特定阈值(例如500000)以上的人提取薪水?

您可以使用列表推导根据条件过滤列表的项目:

[ (k, v) for k, v in data.items() if "Salary" in v ]

You need to see whether "Salary" is in the dictionary or not, like: 您需要查看字典中是否包含“薪水”,例如:

if "Salary" in name[1] and name[1]["Salary"]>500000:
   print(name)

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

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