创建在字典中给出的数值键列表

问题描述:

我有一本字典,看起来像这样:创建在字典中给出的数值键列表

child_parent={} 
child_parent[1]=0 
child_parent[2]=0 
child_parent[3]=2 
child_parent[4]=2 

如果给0我怎么能找到的所有键成一个列表,其中的值是0,其为Python的?的0

最终的结果是[1,2]和2 [3,4]

使用列表理解在字典的items

[k for k, v in child_parent.items() if v == 0] 

 

>>> [k for k, v in child_parent.items() if v == 0] 
[1, 2] 

>>> [k for k, v in child_parent.items() if v == 2] 
[3, 4] 

您可以使用list comprehension

In [62]: [k for k,v in child_parent.iteritems() if v==0] 
Out[62]: [1, 2] 

def find_keys(d, x): 
    return [key for key in d if d[key] == x] 

此操作遍历字典d中的每个键,并创建对应于值x的所有键的列表。

如果您只做过一次,请在其他答案中使用列表理解方法。

如果你这样做多次,创建一个新的字典,通过价值指标键:

from collections import dictdefault 

def valueindex(d): 
    nd = dictdefault(list) 
    for k,v in d.iteritems(): 
     nd[v].append(k) 
    return nd 

parent_child = valueindex(childparent) 
assert parent_child[0] == [1,2] 
assert parent_child[1] == [3,4]