3

In PHP I use the array_column() function a lot as it allows me to retrieve values from a specific column inside an array returned themselves in a nice array, for example, using this array:

$users = [
    [
        'id' => 1,
        'name' => 'Peter'
    ],
    [
        'id' => 2,
        'name' => 'Paul'
    ],
    [
        'id' => 3,
        'name' => 'John'
    ]
];

Doing array_column($users, 'name') will return:

Array
(
    [0] => Peter
    [1] => Paul
    [2] => John
)

Since transitioning to Python I still haven't found a built in function that I can use to do the same thing on a list of dicts for example.

Does such a function exist and if not, what is the best way to achieve this?

Peter Featherstone
  • 7,835
  • 4
  • 32
  • 64

2 Answers2

6

You can use a list comprehension to extract the 'column' of interest. There is no direct Python function to my knowledge. List comprehensions are almost always faster than using map. Python List Comprehension Vs. Map

users = [
    {
        'id': 1,
        'name': 'Peter'
    },
    {
        'id': 2,
        'name': 'Paul'
    },
    {
        'id': 3,
        'name': 'John'
    }
]

>>> [(user.get('id'), user.get('name')) for user in users]
[(1, 'Peter'), (2, 'Paul'), (3, 'John')]

Or using an enumerated index location instead of the id field:

>>> [(n, user.get('name')) for n, user in enumerate(users)]
[(0, 'Peter'), (1, 'Paul'), (2, 'John')]

Or just the names...

>>> [user.get('name') for user in users]
['Peter', 'Paul', 'John']
Peter Featherstone
  • 7,835
  • 4
  • 32
  • 64
Alexander
  • 105,104
  • 32
  • 201
  • 196
1

Something like this?

arr = [
        {
        'id' : 1,
        'name' : 'Peter'
        },
    {
        'id' : 2,
        'name' : 'Paul'
    },
    {
        'id' : 3,
        'name' : 'John'
    }
]
list(map(lambda x: x["name"], arr))
Alexander Ejbekov
  • 5,594
  • 1
  • 26
  • 26
  • That definitely does the job but I'm assuming this means there is no built in function such as `array_column` that does this all behind the scenes? – Peter Featherstone Aug 01 '17 at 16:03
  • @PeterFeatherstone no, there isn't. A "list of dicts" is your own, composite data-structure. You have to deal with it explicitly. Also, while people tend to use list-of-dicts quite often, I think it is almost always better to use a list of namedtuples. – juanpa.arrivillaga Aug 01 '17 at 16:11
  • @juanpa.arrivillaga Fair point and thanks for the explanation :-) – Peter Featherstone Aug 01 '17 at 16:14
  • @PeterFeatherstone Note, I would say list-comprehensions are favored over `list(map(...))` unless the function you are mapping is a built-in, something like `map(int, list_of_number_strings)` – juanpa.arrivillaga Aug 01 '17 at 16:15