-1

Is there a better way to write this block?

    accident2019 = []
    accident2020 = []
    accident2021 = []
    accident2022 = []

    if year == 2019:
        year_list = accident2019
    elif year == 2020:
        year_list = accident2020
    elif year == 2021:
        year_list = accident2021
    elif year == 2022:
        year_list = accident2022

Using string concatenation with "accident" + "year" causes Python to "forget" that accident2019 is a list, so when I try to iterate over the list, I get the characters of the word "accident2019"

Bruce Banner
  • 193
  • 1
  • 12

2 Answers2

3

Instead create a dict where the keys are the years and the values a list ;-)

accidents_by_year = {
    2019: [],
    2020: [],
    2021: [],
    2022: []

}

But Python has something even better for such requirements:

from colections import defaultdict

accidents_by_year = defaultdict(list)

# example use: 
for item in items:
    ... some processing ...
    accidents_by_year[item['year']].append(some_result)
    ... some processing ...

As you can see, you don't even need to pre-create each key in order ot be able to apprend to them. It'll create the key if not present and the value will be an empty list.

DevLounge
  • 8,313
  • 3
  • 31
  • 44
0

You can create a dictionary for that. Instead of if.

accident2019 = [2019]
accident2020 = []
accident2021 = []
accident2022 = []
year=[2019,2020,2021,2022]
accident=[accident2019,accident2020,accident2021,accident2022]

test=dict(zip(year,accident))

year=2019
print(test[year])

  • output
[2019]
DevScheffer
  • 491
  • 4
  • 15