-1

Id like to turn a list of dictionaries to a list that only contains the values to each url property.

So it would work like this:

Input

[
  {"id": 0, "url": "https://example.com/0"},
  {"id": 1, "url": "https://example.com/1"},
  {"id": 2, "url": "https://example.com/2"},
  {"id": 3, "url": "https://example.com/3"},
]

Output

[
  "https://example.com/0",
  "https://example.com/1",
  "https://example.com/2",
  "https://example.com/3",
]

With Javascript I would just use map and return the url values.

nandesuka
  • 699
  • 8
  • 22

3 Answers3

0

list comprehension

Use a simple list comprehension:

l = [
  {"id": 0, "url": "https://example.com/0"},
  {"id": 1, "url": "https://example.com/1"},
  {"id": 2, "url": "https://example.com/2"},
  {"id": 3, "url": "https://example.com/3"},
]

[d['url'] for d in l]

output:

['https://example.com/0',
 'https://example.com/1',
 'https://example.com/2',
 'https://example.com/3']

map + itemgetter

or, map + operator.itemgetter

from operator import itemgetter
list(map(itemgetter('url'), l))

output:

['https://example.com/0',
 'https://example.com/1',
 'https://example.com/2',
 'https://example.com/3']
mozway
  • 194,879
  • 13
  • 39
  • 75
0
ld = [
  {"id": 0, "url": "https://example.com/0"},
  {"id": 1, "url": "https://example.com/1"},
  {"id": 2, "url": "https://example.com/2"},
  {"id": 3, "url": "https://example.com/3"},
]
lurl1 = [x["url"] for x in ld]  # more idiomatic list comprehension
lurl2 = list(map(lambda x: x["url"], ld))  # if you really want map
ljmc
  • 4,830
  • 2
  • 7
  • 26
0

Using a list comprehension would be the idiomatic way to go:

result = [x['url'] for x in original_list]
Mureinik
  • 297,002
  • 52
  • 306
  • 350