0

I have the following array:

[
  {"Name": "abc", "Age": 10},
  {"Name": "xyz", "Age": 12},  
  {"Name": "def", "Age": 15}
]

I want to create the following array out of it:

["abc","xyz","def"]

ie just take the name field out of each object. Is there an easier way to do it other than through a loop?

Noel
  • 83
  • 2
  • 2
  • 8

4 Answers4

1

You can use a single line list comprehension:

d = [
  {"Name": "abc", "Age": 10},
  {"Name": "xyz", "Age": 12},  
  {"Name": "def", "Age": 15}
]

data = [i["Name"] for i in d]

Output:

['abc', 'xyz', 'def']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
1

You have an error in the dictionary syntax, I'm assuming you wanted to use string keys.

The issue could be solved using list comprehensions:

data = [
  {'Name': 'abc', 'Age': 10},
  {'Name': 'xyz', 'Age': 12},
  {'Name': 'def', 'Age': 15}
]

print([item['Name'] for item in data]) #=> ['abc', 'xyz', 'def']

You could use map to avoid using loops, but it's not pythonic:

map(lambda i: i['Name'], data)
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
  • Fixed the dictionary syntax in the question. I was thinking of the map version. But if it is not pythonic, then I guess I will go with the loop approach. Thanks. – Noel Sep 11 '17 at 23:25
0
your_nested_list = [
  {Name: "abc", Age: 10},
  {Name: "xyz", Age: 12},  
  {Name: "def", Age: 15}
]


result = []
for dict in your_nested_list:
    result.append(dict[Name])

In this code you iterate over dictionaries in your nested list and append values of thekey Name.

MarianD
  • 13,096
  • 12
  • 42
  • 54
0

Without a loop - but you need to know in advance the number of your dictionaries in your list and be sure that in every of them is the key Name:

your_nested_list = [
  {Name: "abc", Age: 10},
  {Name: "xyz", Age: 12},  
  {Name: "def", Age: 15}
]

result = [
    your_nested_list[0][Name], 
    your_nested_list[1][Name], 
    your_nested_list[2][Name],
    ]

Ugly enough, isn't it?

MarianD
  • 13,096
  • 12
  • 42
  • 54