-2

This is probably very simple but i cant figure it out :(

Im trying to get the list of all captions form the list below

mylist = [{'Caption': 'obj1'},{'Caption': 'obj2'},{'Caption': 'obj3'}]
print(mylist)

captions = map(lambda o: o.Caption, mylist)

but im getting AttributeError: 'dict' object has no attribute 'Caption'

i can write the same in Ansible {{ mylist | map(attribute='Caption')|list}} but no idea in Python :(

Marek
  • 127
  • 1
  • 8
  • 2
    `captions = map(lambda o: o["Caption"], mylist)` - this is python, not js. alternatively: `captions = map(lambda o: o.get("Caption"), mylist)` – Patrick Artner Oct 09 '20 at 04:50
  • You have a list of dictionaries. See this answer https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops – Mace Oct 09 '20 at 04:51
  • Whats your expected output here? `map` will return a `map` object unless you cast it to `list` etc. – PacketLoss Oct 09 '20 at 04:53

3 Answers3

1

You need to use dict[key] in python.

You can also use .get(key).

captions = map(lambda o: o['Caption'], mylist)
captions = map(lambda o: o.get('Caption'), mylist)

If you are new to python, you can try reading this to learn about creating dicts, keys, accessing, iterating, and modifying.

https://www.datacamp.com/community/tutorials/dictionary-python

Also, note that map will return an iterator, you can call list on it to create a list from it.

list(map(...))
Uriya Harpeness
  • 628
  • 1
  • 6
  • 21
0

Given your example in Ansible/jinja.

To match your exact output from;

{{ mylist | map(attribute='Caption')|list}}

You will need to ensure you cast the map() iterator to a list.

captions = list(map(lamba o: o.get('Caption'), mylist))

Ansible returns a list when you specify |list after your map() where as pure Python returns a map object

>>> captions = map(lambda o: o['Caption'], mylist)
>>> captions
#<map object at 0x03BA5130>


>>> list(map(lambda o: o['Caption'], mylist))
#['obj1', 'obj2', 'obj3']
PacketLoss
  • 5,561
  • 1
  • 9
  • 27
0

Solution: To access keys from dictionary in python you either need to use .get(key) or dict[key] syntax.

mylist = [{'Caption': 'obj1'},{'Caption': 'obj2'},{'Caption': 'obj3'}]
print(mylist)

captions = map(lambda o: o.get('Caption'), mylist)
print(list(captions)) # Because map will return an iterator, so you have to call list on the iterator to create a list out of it.

captions = map(lambda o: o['Caption'], mylist)
print(list(captions)) # Because map will return an iterator, so you have to call list on the iterator to create a list out of it for printing
Piyush Sambhi
  • 843
  • 4
  • 13