Home > Enterprise >  crating a new list based on the conditions of the dictionary nested in the list
crating 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 that 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)
  • Related