Search code examples
list-comprehensionnested-for-loop

extract dictionary elements from nested list in python


I have a question.

I have a nested list that looks like this.

x=    [[{'screen_name': 'BreitbartNews',
   'name': 'Breitbart News',
   'id': 457984599,
   'id_str': '457984599',
   'indices': [126, 140]}],
 [],
 [],
 [{'screen_name': 'BreitbartNews',
   'name': 'Breitbart News',
   'id': 457984599,
   'id_str': '457984599',
   'indices': [98, 112]}],
 [{'screen_name': 'BreitbartNews',
   'name': 'Breitbart News',
   'id': 457984599,
   'id_str': '457984599',
   'indices': [82, 96]}]]

There are some empty lists inside the main list. What I am trying to do is to extract screen_name and append them as a new list including the empty ones (maybe noting them as 'null').

y=[]
for i in x :
    for j in i :
        if len(j)==0 :
            n = 'null'
        else :
            n = j['screen_name']
    y.append(n)    

I don't know why the code above outputs a list,

['BreitbartNews',
 'BreitbartNews',
 'BreitbartNews',
 'BreitbartNews',
 'BreitbartNews']

which don't reflect the empty sublist.

Can anyone help me how I can refine my code to make it right?


Solution

  • You are checking the lengths of the wrong lists. Your empty lists are in the i variables.

    The correct code would be

    y=[]
    for i in x :
        if len(i) == 0:
            n = 'null'
        else:
            n = i[0]['screen_name']
        y.append(n)
    

    It may help to print(i) in each iteration to better understand what is actually happening.