Python 在字典中创建给定值的键列表

Python 在字典中创建给定值的键列表,python,Python,我有一本这样的字典: child_parent={} child_parent[1]=0 child_parent[2]=0 child_parent[3]=2 child_parent[4]=2 如果给定0,我如何在值为0的pythonic列表中查找所有键 0的最终结果是[1,2],而对于2[3,4]则使用对dict的项的列表理解: [k for k, v in child_parent.items() if v == 0] 对dict的项使用列表理解: [k for k, v in c

我有一本这样的字典:

child_parent={}
child_parent[1]=0
child_parent[2]=0
child_parent[3]=2
child_parent[4]=2
如果给定0,我如何在值为0的pythonic列表中查找所有键


0的最终结果是[1,2],而对于2[3,4]

则使用对dict的
项的列表理解:

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


对dict的
项使用列表理解:

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

您可以使用:

您可以使用:

这将迭代字典
d
中的每个键,并从与value
x
对应的所有键中创建一个列表


这将迭代字典
d
中的每个键,并从与value
x

对应的所有键中创建一个列表。如果只执行一次,请使用其他答案中的列表理解方法

如果要多次执行此操作,请创建一个新的dict,该dict通过值对键进行索引:

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]

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

如果要多次执行此操作,请创建一个新的dict,该dict通过值对键进行索引:

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]
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]