user10332249
user10332249

Reputation:

How to iterate through a list of dictionaries, take the value of a condition and add it to a new list?

So I got a big list with dictionaries inside it. Here is a small example of one of the dictionaries:

[{'id': 32,
'calls': 1,
'wounded': 2,
'dog': True,
'hitrun': 'David Williams'},
{'id': 384,

I want to iterate through these dictionaries, get the value of calls and wounded if they're bigger than 0 and add these values to a new list. I tried doing this:

lijst = []
for x in nee:
if x['calls'] > '0':
    list.append(x)
if x['wounded'] > '0':
    list.append(x)

But this doesn't work. There are also some calls and wounded with None as their value, so the > 0 doesn't work either

Upvotes: 1

Views: 1592

Answers (3)

schlodinger
schlodinger

Reputation: 559

You can try this:

data = [
    {'id': 32,
    'calls': '1',
    'wounded': '2',
    'dog': True,
    'hitrun': 'David Williams'},
    {'id': 32,
    'calls': None,
    'wounded': None,
    'dog': True,
    'hitrun': 'David Williams'}
]
call_wounded_list = [dict_[f] for dict_ in data for f in ['calls', 'wounded'] if str(dict_[f]).isdigit() and float(dict_[f]) > 0]

this returns

>>> call_wounded_list
['1', '2']

Upvotes: 0

marcos
marcos

Reputation: 4510

You can use a nested list comprehension, because you need to iterate over your data and your conditions, for example, something like this:

data = [
    {'id': 32,
    'calls': '1',
    'wounded': '2',
    'dog': True,
    'hitrun': 'David Williams'},
    {'id': 32,
    'calls': None,
    'wounded': None,
    'dog': True,
    'hitrun': 'David Williams'}
]

output = [
    x[field] for x in data for field in ['calls', 'wounded'] if x[field] is not None and int(x[field]) > 0
]

print(output)
>>> ['1', '2']

Upvotes: 1

JacobIRR
JacobIRR

Reputation: 8946

This works:

nee = [{'id': 32,
'calls': 1,
'wounded': 2,
'dog': True,
'hitrun': 'David Williams'}]

l = []
for x in nee:
  if x['calls'] > 0:
    l.append(x['calls'])
  if x['wounded'] > 0:
    l.append(x['wounded'])

print(l)

You can also sum two list comprehensions:

wounded = [x['wounded'] for x in nee if x['wounded'] > 0]
calls = [x['calls'] for x in nee if x['calls'] > 0]
new_list = wounded + calls
print(new_list)

Upvotes: 0

Related Questions