0

I am working on a python assignment struggling with list comprehension. Basically this is the nested for loop I need to convert into a list comprehension function:

for driver in standings: 
    if driver['driver'] in drivers_with_points.keys():
        driver['points'] = drivers_with_points[driver['driver']]

This is the question prompt:

    """Updates the < standings > list by adding the points from the given race < results >.

    Using a list comprehension, updates each dictionary in < standings > at
    the key 'points' with the points value retrieved from the < drivers_with_points >
    dictionary.

    Parameters:
        standings (list): A list of dictionaries, each containing information about a
        driver's standing.

        drivers_with_points (dict): A dictionary containing the name and points scored
        by each driver who scored points in a race.

    Returns:
        None
    """
Rayan Hatout
  • 640
  • 5
  • 22
CKay
  • 21
  • 1
  • That isn't a nested loop. Does this answer your question? [if/else in a list comprehension](https://stackoverflow.com/questions/4260280/if-else-in-a-list-comprehension) – Pranav Hosangadi Mar 29 '22 at 01:17

1 Answers1

0

The solution might look something like:

drivers_with_points = {"joe": 22, "dan": 123}  # dummy data
drivers = [{"driver": "joe"}, {"driver": "dan"}]  # dummy data

standings = [
    {"points": drivers_with_points[driver["driver"]]}
    for driver in drivers
    if driver["driver"] in drivers_with_points.keys()
]  # list comprehension


print(standings)  # Output: [{'points': 22}, {'points': 123}]

I took my freedom to use some dummy-data here, as you did not provide any datasets the script is supposed to work with.

Bialomazur
  • 1,122
  • 2
  • 7
  • 18