Python 根据现有列表筛选字典

Python 根据现有列表筛选字典,python,list,dictionary,genetics,Python,List,Dictionary,Genetics,还是一个Python新手,所以请对我放松点 我已经准备好了一本字典: new_dict 我想筛选以返回键,其中每个键所附加的任何值都与我设置的现有列表中的值匹配: list(data.Mapped_gene) 有什么想法吗 编辑: 我还是没能做到这一点 如果有帮助,csv表和键都是字符串 以下是扩展理解的完整代码: import csv new_dict = {} with open(raw_input("Enter csv file (including path)"), 'rb'

还是一个Python新手,所以请对我放松点

我已经准备好了一本字典:

new_dict
我想筛选以返回键,其中每个键所附加的任何值都与我设置的现有列表中的值匹配:

list(data.Mapped_gene)
有什么想法吗

编辑: 我还是没能做到这一点

如果有帮助,csv表和键都是字符串

以下是扩展理解的完整代码:

import csv    
new_dict = {}
with open(raw_input("Enter csv file (including path)"), 'rb') as f:
  reader = csv.reader(f)
  for row in reader:
    if row[0] in new_dict:
      new_dict[row[0]].append(row[1:])
    else:
      new_dict[row[0]] = row[1:]
print new_dict

#modified from: http://bit.ly/1iOS7Gu
import pandas
colnames = ['Date Added to Catalog',    'PUBMEDID', 'First Author', 'Date',     'Journal',  'Link', 'Study',    'DT',   'Initial Sample Size',  'Replication Sample Size',  'Region',   'Chr_id',   'Chr_pos',  'Reported Gene(s)', 'Mapped_gene',  'p-Value',  'Pvalue_mlog',  'p-Value (text)',   'OR or beta',   '95% CI (text)',    'Platform [SNPs passing QC]',   'CNV']
data = pandas.read_csv('C:\Users\Chris\Desktop\gwascatalog.csv', names=colnames)


my_list = list(data.Mapped_gene)
my_set = set(my_list)

[k for k, v in new_dict.items() if any(x in my_set for x in v)]
错误消息:
“TypeError:不可损坏的类型:'列表'”

使用
any
和列表理解:

my_list = list(data.Mapped_gene)
keys = [k for k, v in new_dict.items() if any(x in my_list for x in v)]
(k for k, v in my_dict.iteritems() if v in gene_set)

如果
my_list
很大,则首先将其转换为
set
,因为它提供
O(1)
查找。

要提高查找性能,请将列表转换为set

gene_set = set(data.Mapped_gene)
然后使用如其他示例所示的列表理解或字典理解 如果你也对价值感兴趣

{k:v for k, v in my_dict.iteritems() if v in gene_set}
如果
my_dict
很大,则
my_dict
上的方法
iteritems()
特别有用。为了提高方法的内存效率,您可以使用生成器而不是列表或词典:

my_list = list(data.Mapped_gene)
keys = [k for k, v in new_dict.items() if any(x in my_list for x in v)]
(k for k, v in my_dict.iteritems() if v in gene_set)

值存储在列表/元组中?这看起来很棒。如何获得输出?@user3297046查看更新的答案。将列表理解的返回值存储在变量中。仍然无法使其正常工作。请参阅上面编辑的问题。@user3297046看起来您有一个列表,请尝试使用:
my_set=set(y代表y,在my_列表中的x代表y,在x中的y)
@AshwiniChaudhary我认为编译器会对此进行优化。但也许不行,因为“set”这个名字可以被称为“set”,谢谢。更新。