Home > front end >  Creating a new list based on the conditions of the dictionary nested in the list
Creating a new list based on the conditions of the dictionary nested in the list

Time:10-10

I am new to Python. I am trying to create a new list based on a specific condition, which is fruits['type'] === 'edit'.

fruits = [{'type': 'edit',
  'ns': 0,
  'title': 'List',
  'pageid': 39338740},
 {'type': 'new',
  'ns': 0,
  'title': 'John Braid',
  'pageid': 8164456},
 {'type': 'edit',
  'ns': 0,
  'title': 'lokan',
  'pageid': 65869267}]

My code returns an empty array:

newlist = []

for x in fruits:
  if x['type'] == 'edit' in x:
    newlist.append(x)

print(newlist)

CodePudding user response:

fruits = [{'type': 'edit',
  'ns': 0,
  'title': 'List',
  'pageid': 39338740},
 {'type': 'new',
  'ns': 0,
  'title': 'John Braid',
  'pageid': 8164456},
 {'type': 'edit',
  'ns': 0,
  'title': 'lokan',
  'pageid': 65869267}]

newlist = [fruit for fruit in fruits if fruit["type"] == "edit"]

print(newlist)

CodePudding user response:

You can create new list with list comprehension,

new_list = [d for d in fruits if d['type'] == 'edit']

Which is equal to,

new_list = [] 
for d in fruits:
    if d['type'] == 'edit':
         new_list.append(d)

CodePudding user response:

for x in fruits:
    try:
        if x['type'] == 'edit':
            newlist.append(x)
    except:
        pass

print(newlist)

CodePudding user response:

Your code didn't work, as you included in x in your if statement, which was already answered. But I wanted to include further explanation, which hopefully will be helpful.

x['type'] == 'edit' evaluates to True or False which means that your code:

if x['type'] == 'edit' in x

actually looks like that when you intended it to append to the list:

if True in x

And True is, of course, not an element of x, so this is False, so your list never is appended.

  • Related