Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

python - How to check if the first element of each tuple inside a list is a key of a dictionary?

For instance, if there's a dictionary student_gpa where:

student_gpa = {'Alex': 3.00, 
               'John': 3.50,
               'Jennifer': 3.75}

and a list of tuples student_age where:

student_age = [('Mike', 14),
              ('Alex', 13),
              ('John', 15)]

How do I check if 'Mike', 'Alex', and 'John' are all keys inside the dictionary student_gpa?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To check if an object is a key in a dict you can call dict.keys() which will return a list of all keys in the dict.

name in dict.keys()

However, if you just want to check that all your students exist in the dict you can use all() and a loop to determine if all names are found within the list of keys.

>>> all(student in student_gpa.keys() for student, age in student_age)
#False

>>> student_gpa['Mike'] = 1.0
>>> all(student in student_gpa.keys() for student, age in student_age)
#True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...