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?

0

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

Comments

1

Something like this?

arr = [
        {
        'id' : 1,
        'name' : 'Peter'
        },
    {
        'id' : 2,
        'name' : 'Paul'
    },
    {
        'id' : 3,
        'name' : 'John'
    }
]
list(map(lambda x: x["name"], arr))

4 Comments

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?
@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 Fair point and thanks for the explanation :-)
@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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.