Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get specific list by value python

I have a list of dictionary looks like this.

charts = [[{'select': 'scatter-form'}], [{'select': 'line-form'}]]

I want to get the list by the value of 'select' key.
For example:

scatterform = [{'select': 'scatter-form'}]
lineform = [{'select': 'line-form'}]

this one is not working because of some error list indices must be integers or slices, not str

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

New answer:

Since the original post is edited, I updated my answer.

First, If you certain that the ‘select’ value is unique and not missing,

charts = [[{'select': 'scatter-form'}], [{'select': 'line-form'}]]

scatterform = None
lineform = None
for chart in charts:
    if chart[0]['select'] == 'scatter-form':
        scatterform = chart
    elif chart[0]['select'] == 'line-form':
        lineform = chart
assert scatterform is not None
assert lineform is not None

will work.
or, if there could be many same ‘select’ values or could be none, you can do following:

charts = [[{'select': 'scatter-form'}], [{'select': 'line-form'}]]

scatterforms = [chart for chart in charts if chart[0]['select'] == 'scatter-form']
lineforms = [chart for chart in charts if chart[0]['select'] == 'line-form']
print(scatterforms, lineforms)

output:

[[{'select': 'scatter-form'}]] [[{'select': 'line-form'}]]

Old answer:

charts is a nested list. You should iterate it.

charts = [[{'select': 'scatter-form'}], [{'select': 'line-form'}]]


for [chart] in charts:
    if chart['select'] == "scatter-form":
       print("scatter-form") or [{'select': 'scatter-form'}]
    if chart['select'] == "line-form":
       print("line-form") or [{'select': 'line-form'}]

output:

scatter-form
line-form

or

for chart in charts:
    if chart[0]['select'] == "scatter-form":
       print("scatter-form") or [{'select': 'scatter-form'}]
    if chart[0]['select'] == "line-form":
       print("line-form") or [{'select': 'line-form'}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading