0

I have a long list of dictionaries like this:

dict_data = [{'country': 'canada', 'province': 'alberta', 'city': 'calgary', 'sales': 1450, 'date': ['14', '02', '2021']}, {'country': 'canada', 'province': 'ontario', 'city': 'toronto', 'sales': 2003, 'date': ['12', '02', '2021']}]

I need to filter the sales data by month to perform calculations on them. But I am stuck on how to access dictionary values by key, when the values are a list. To start with I am trying to convert the date strings into integers.

for row in dict_data: 
    row['date'] = int(row['date'])

I get an error "TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'". Similar to this method worked for splitting the date up into separate strings.

I thought I would be able to access the list values for date by using something along the lines of dict_data['date'][1] to access the month, but that doesn't work either, I am assuming because I have a list of dictionaries and not just one? Do I need to iterate through the list of dictionaries and how do I do that?

  • Does this answer your question? [Convert all strings in a list to int](https://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int) – Nick May 14 '21 at 01:14
  • Does this answer your question? [Python list of dictionaries search](https://stackoverflow.com/questions/8653516/python-list-of-dictionaries-search) – Abhijeet May 14 '21 at 01:15
  • `row['data']` is a list, so you need to convert all values individually e.g. `row['date'] = list(map(int, row['date']))` – Nick May 14 '21 at 01:15

1 Answers1

0

For a problem like this I would use map.

dict_data = [{'country': 'canada', 'province': 'alberta', 'city': 'calgary', 'sales': 1450, 'date': ['14', '02', '2021']}]
for loc in dict_data:
    loc['date'] = list(map(int,loc['date']))

Also, you can't do this int([1,2,3]). You can either use map or list comprehension.

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44