[英]Python - A list of dictionaries, accessing values by key when the values are a list
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'".我收到一个错误“TypeError:int() 参数必须是一个字符串,一个类似字节的 object 或一个数字,而不是‘列表’”。 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?我以为我可以通过使用类似于 dict_data['date'][1] 的东西来访问月份来访问日期的列表值,但这也不起作用,我假设因为我有一个列表字典,而不仅仅是一个? Do I need to iterate through the list of dictionaries and how do I do that?
我需要遍历字典列表吗?我该怎么做?
For a problem like this I would use map
.对于这样的问题,我会使用
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])
.此外,您不能这样做
int([1,2,3])
。 You can either use map or list comprehension.您可以使用 map 或列表理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.