猿问

在列表中过滤字典

我需要dictionary在内过滤list。我的数据如下所示:


[('John', 'Samantha', {'source': 'family'}),

 ('John', 'Jill', {'source': 'work'})]

我需要使用过滤记录source=family,我尝试了以下操作,但没有成功:


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

非常感谢您的帮助!


qq_遁去的一_1
浏览 152回答 3
3回答

慕丝7291255

在您的列表理解中,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']等。作为程序员,您始终必须检查这些假设。

紫衣仙女

我建议您基于理解,采用以下解决方案,仅假设字典中始终有一个名为“源”的键,如您在评论中所述: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 elementsmy_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')]

米脂

您可以使用过滤器功能过滤列表>>> li = [('John', 'Samantha', {'source': 'family'}),...  ('John', 'Jill', {'source': 'work'})]>>>>>> filtered = list(filter(lambda x: x[2]['source'] == 'family', li))>>>>>> filtered[('John', 'Samantha', {'source': 'family'})]>>>
随时随地看视频慕课网APP

相关分类

Python
我要回答