Что-то вроде этого, может быть? Я предположил, что поле «Группы» должно быть разделено и не использоваться как «есть». Обновлено в соответствии с комментариями для чтения всех групп.
import csv
import io
import random
import collections
import itertools
# Data included in source for clarity
car_csv = """
"Car code","Price","Alias","Groups"
"Car1","100","Blue Car","Cheap Cars"
"Car2","900","Gold Car","Expensive Cars"
"Car3","150","Red Car","Cheap Cars"
"Car4","999","Platinum Car","Expensive Cars"
"Car5","122","Brown Car","Cheap Cars"
"Car6","500","Pink Car","Cheap Cars","Expensive Cars"
"TestCarWithThreeGroups","500","Pink Car","Cheap Cars","Expensive Cars","Broken Cars"
""".lstrip()
indicator_csv = """
"Indicator_Field","Indicator_Value","Desc","Groups"
"Fault","Rusting","Bodywork is rusting","Cheap Cars; Expensive Cars"
"Error","Window Winder Stopped","Manual window winder broken","Cheap Cars"
"Fault","V12 Issues","V12 Engine Problems","Expensive Cars"
""".lstrip()
# Read data (replace io.StringIO(...) with a file object to read from a file)
indicator_data = list(csv.DictReader(io.StringIO(indicator_csv)))
# Note `restkey` to capture all of the additional columns into `OtherGroups`.
car_data = list(csv.DictReader(io.StringIO(car_csv), restkey='OtherGroups'))
# Pre-massage the car data so `Groups` is always a set of groups, and `OtherGroups` is no longer there:
for car in car_data:
car['Groups'] = {car['Groups']} | set(car.pop('OtherGroups', ()))
# Create a mapping of groups <-> indicators
indicators_by_group = collections.defaultdict(list)
for indicator in indicator_data:
for group in indicator['Groups'].split('; '):
indicators_by_group[group].append(indicator)
def generate_car():
car = random.choice(car_data)
# Concatenate all indicators based on the groups of the car
available_indicators = list(itertools.chain(
*(indicators_by_group.get(group, []) for group in car['Groups'])
))
# Choose a random indicator -- this will crash if there are no available indicators
# for the car.
indicator = random.choice(available_indicators)
# Generate output datum
return {
'code': car['Car code'],
indicator['Indicator_Field']: indicator['Indicator_Value'],
}
for x in range(10):
print(generate_car())
Пример вывода:
{'code': 'Car1', 'Error': 'Window Winder Stopped'}
{'code': 'Car6', 'Error': 'Window Winder Stopped'}
{'code': 'Car2', 'Fault': 'Rusting'}
{'code': 'Car6', 'Error': 'Window Winder Stopped'}
{'code': 'TestCarWithThreeGroups', 'Error': 'Window Winder Stopped'}
{'code': 'Car5', 'Fault': 'Rusting'}
{'code': 'Car2', 'Fault': 'Rusting'}
{'code': 'TestCarWithThreeGroups', 'Fault': 'V12 Issues'}
{'code': 'Car6', 'Fault': 'Rusting'}
{'code': 'TestCarWithThreeGroups', 'Error': 'Window Winder Stopped'}