This works, according to the documentation:
>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> list(map(operator.itemgetter(1), inventory))
[3, 2, 5, 1]
Now I want to do something similar, for a list of dicts:
>>> data = [{'xxx': 'x'}, {'xxx': 'y'}]
>>> list(map(operator.attrgetter('xxx'), data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'xxx'
I was expecting:
['x', 'y']
But it seems attrgetter
does not work for dictionaries (only for classes?). How can I setup an "element getter" for dictionaries?