过滤字典列表 [英] Filter list of dictionaries

查看:98
本文介绍了过滤字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的示例:

dictlist = [{'first': 'James', 'last': 'Joule'}, 
            {'first': 'James','last': 'Watt'},
            {'first': 'Christian','last': 'Doppler'}]

我正在尝试获取姓氏.如果在模型中,则代码为:

I am trying to get the last name. If this was in a model, the code would be:

getdata = Name.objects.filter(name="Christian")
getLastName = getdata.last

我会得到"Doppler".

推荐答案

这是具有列表理解功能的非常简单的解决方案:

This is very simple solution with list comprehension:

>>> dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
>>> [x['last'] for x in dictlist if x['first'] == 'Christian']
['Doppler']

这篇关于过滤字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆