-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
  • 449
  • 3
  • 13

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
  • 81,317
  • 8
  • 19
  • 49
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
  • 912
  • 2
  • 14
0

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

result = [x['url'] for x in original_list]
Mureinik
  • 277,661
  • 50
  • 283
  • 320