Baobab1988
Baobab1988

Reputation: 715

How to pass json list values into python list?

My json data will print all the items of my emailList when I do this:

        print(data['emailList'])

and it will return this:

[
{
'emailId': 987654321,
'customerId': 123456789,
},
{
'emailId': 56789,
'customerId': 8765,
}
]

How could I include all the possible values for customerId into my final_list? I've tried this:

 final_list = []
    for each_requ in data:
        final_list.append(each_requ)[emailList][customerId]
    return final_list

but received this error:

 TypeError: list indices must be integers or slices, not str

desired output:

    [123456789 ,8765]

Upvotes: 0

Views: 58

Answers (2)

Beny Gj
Beny Gj

Reputation: 615

here the solution


your_json = [{'emailId': 987654321, 'customerId': 123456789},
 {'emailId': 56789, 'customerId': 8765}]

[i['customerId'] for i in your_json]  
[123456789, 8765]

so for your code, you can do something like that

email_list = data['emailList']
result = [i['customerId'] for i in email_list] 

or single line

result = [i['customerId'] for i in data['emailList']] 

with map

result = list(map(lambda x: x['customerId'], data['emailList'])) 

Upvotes: 2

akhter wahab
akhter wahab

Reputation: 4085

 final_list = []
    for each_requ in data:
        final_list.append(each_requ['customerId'])
    return final_list

this should return your desired results if json like dict is in data variable

Upvotes: 0

Related Questions