在列表中过滤字典

时间:2018-08-14 09:35:39

标签: python python-3.x dictionary

我需要过滤"launchUrl": "http://localhost:5000/swagger"中的dictionary。我的数据如下:

list

我需要使用[('John', 'Samantha', {'source': 'family'}), ('John', 'Jill', {'source': 'work'})] 过滤记录,我尝试了以下操作,但没有成功:

source=family

非常感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

在列表理解中,i是元组之一,因此('John', 'Samantha', {'source': 'family'})('John', 'Jill', {'source': 'work'})。那不是字典,所以你不能像字典一样对待它!

如果您的元组始终由3个元素组成,而第3个元素是带有source键的字典,请使用:

[i for i in my_list if i[2]['source'] == 'family']

如果这些假设中的任何一个都不成立,则必须添加更多代码。例如,如果词典始终在那儿,但是'source'键可能丢失,那么您可以使用dict.get()来在键不存在时返回默认值:

[i for i in my_list if i[2].get('source') == 'family']

如果元组的长度可以变化,但是字典始终是最后一个元素,则可以使用负索引:

[i for i in my_list if i[-1]['source'] == 'family']

等作为程序员,您始终必须检查这些假设。

答案 1 :(得分:0)

我建议您基于理解,采用以下解决方案,仅假设字典中始终有一个名为“源”的键,如您在评论中所述:

my_list = [('John', 'Samantha', {'source': 'family'}),
           ('John', 'Jill', {'source': 'work'}),
           ('Mary', 'Joseph', {'source': 'family'})]

# Keep only elements including a dictionary with key = "source" and value = "family" 
my_filtered_list = [t for t in my_list if any((isinstance(i,dict) and i['source'] == 'family') for i in t)]
print(my_filtered_list)  # [('John', 'Samantha', {'source': 'family'}), ('Mary', 'Joseph', {'source': 'family'})]

# If needed: remove the dictionary from the remaining elements
my_filtered_list = [tuple(i for i in t if not isinstance(i,dict)) for t in my_filtered_list]
print(my_filtered_list)  # [('John', 'Samantha'), ('Mary', 'Joseph')]

答案 2 :(得分:-1)

您可以使用过滤器功能来过滤列表

>>> li = [('John', 'Samantha', {'source': 'family'}),
...  ('John', 'Jill', {'source': 'work'})]
>>>
>>> filtered = list(filter(lambda x: x[2]['source'] == 'family', li))
>>>
>>> filtered
[('John', 'Samantha', {'source': 'family'})]
>>>
相关问题