0

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]
2
  • print(data['emailList'][customerId]) won't print anything. Commented Apr 28, 2020 at 10:13
  • Your "json data" are plain ordinary Python types - in your case a python dict which "emailList" key points to a python list of python dicts. IOW, the fact you got those data from json is totally irrelevant. Commented Apr 28, 2020 at 10:35

2 Answers 2

2

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'])) 
Sign up to request clarification or add additional context in comments.

Comments

0
 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.