如何遍历字典列表,获取条件值并将其添加到新列表中?

时间:2020-02-05 22:22:58

标签: python python-3.x list dictionary nested-lists

所以我有一个很大的列表,里面有字典。这是其中一个词典的一个小例子:

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

我想遍历这些字典,获取调用的值,如果它们大于0,则将它们弄伤,然后将这些值添加到新列表中。我尝试这样做:

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

但这不起作用。还有一些电话,其值无人受伤,因此> 0也不起作用

3 个答案:

答案 0 :(得分:0)

这有效:

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)

您还可以总结两个列表理解:

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)

答案 1 :(得分:0)

您可以使用嵌套列表推导,因为您需要遍历数据和条件,例如,如下所示:

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']

答案 2 :(得分:0)

您可以尝试以下方法:

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]

这将返回

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