-2

I Have this object:

myObj = [{'city':'New York', 'number': 5550}, {'city':'San Francisco', 'number': 0565}]

How could I use list comprehension to store only the _city_ attribute in the list below:

my_new_list = [ HERE THE LIST COMPREHENSION ]

Output should be: "New York", "San Francisco"

Pynchia
  • 10,996
  • 5
  • 34
  • 43
  • 4
    `[d['city'] for d in myObj]`? – jasonharper Jul 22 '20 at 17:39
  • 1
    Just to note your last "number" for the city of "San Francisco" will throw a `SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers` – Jacques Jul 22 '20 at 17:41

2 Answers2

4

Try this:

my_new_list = [item['city'] for item in myObj]

The item value would be {'city':'New York', 'number': 5550} the first time and {'city':'San Francisco', 'number': 0565} the second time. Since these are dictionaries, we can use item['city'] to access the city value from each dictionary.

Krishnan Shankar
  • 780
  • 9
  • 29
  • Upvoted. How could you improve that to cater for a potentially missing `city` attribute? – Pynchia Jul 22 '20 at 18:00
  • Maybe try `my_new_list = [item['city'] for item in myObj if item.get('city')]`. Or, you can use `my_new_list = [item.get('city') for item in myObj]` if you want the `None`s being saved to the list. Also, the second parameter of dict.get() is the value to return when it can't find the requested key, so you can add that too if you want it to save another value to the list like `"not available"`. – Krishnan Shankar Jul 22 '20 at 18:14
0

Here you go:

my_new_list = [row['city'] for row in myObj]

value

['New York', 'San Francisco']
Balaji Ambresh
  • 4,977
  • 2
  • 5
  • 17