0

Without using loops to iterate through a list, is there a preferred syntax for retrieving a value of a given key from all dictionaries in a list?

This is a loop which achieves what I need:

>>> my_list = [{'foo':'bar'},{'foo':'buzz'}]
>>> [x['foo'] for x in my_list]
['bar', 'buzz']

This is intuitively how I think the same result should be achieved:

>>> my_list = [{'foo':'bar'},{'foo':'buzz'}]
>>> [my_list[*]['foo']]
['bar', 'buzz']
Chip Wolf
  • 29
  • 2
  • 2
    What's wrong with looping though the list? No, standard lists don't have that kind of magic syntax. – deceze Jan 20 '21 at 14:28
  • 1
    But... in the end you're looping the list. So what's wrong with having an explicit loop that clearly conveys that instead of some unclear syntax which will just confuse readers? – Tomerikoo Jan 20 '21 at 14:42
  • "This is intuitively how I think the same result should be achieved" then write up a PEP proposing this change, but there is no special syntax. For loops are very pythonic – juanpa.arrivillaga Jan 20 '21 at 15:07

2 Answers2

1

One way is to use map

mylist = [{'foo':'bar'},{'foo':'buzz'}]

def extract(x):
    return x['foo']

a = list(map(extract, mylist))

print(a)
# ['bar', 'buzz']

Or as suggested by deceze in the comments: operator.itemgetter

from operator import itemgetter

mylist = [{'foo':'bar'},{'foo':'buzz'}]
a = list(map(itemgetter('foo'), mylist))
print(a)
# ['bar', 'buzz']
some_programmer
  • 3,268
  • 4
  • 24
  • 59
0

If you don't want any modules, or separate functions,

x = list(map(lambda x: x['foo'], my_list))

print(x)

>>> ['bar', 'buzz']
coderoftheday
  • 1,987
  • 4
  • 7
  • 21