gpt4 book ai didi

python - 在 python 中使用字典值获取字典键

转载 作者:太空宇宙 更新时间:2023-11-04 10:57:54 25 4
gpt4 key购买 nike

我的问题是:如何使用字典值获取字典键?

d={'dict2': {1: 'one', 2: 'two'}, 'dict1': {3: 'three', 4: 'four'}}

我想得到dict2的key的key。

谢谢。

最佳答案

这是一个可以处理任意嵌套字典的递归解决方案:

>>> import collections
>>> def dict_find_recursive(d, target):
... if not isinstance(d, collections.Mapping):
... return d == target
... else:
... for k in d:
... if dict_find_recursive(d[k], target) != False:
... return k
... return False

从长远来看,它的效率不如“反向词典”,但如果您不经常进行此类反向搜索,它可能并不重要。 (请注意,您必须明确地将 dict_find_recursive(d[k], target) 的结果与 False 进行比较,否则会出现像 '' 这样的虚假键导致搜索失败。事实上,如果将 False 用作键,即使此版本也会失败;完全通用的解决方案将使用唯一的哨兵 object() 来指示错误.)

一些用法示例:

>>> d = {'dict1': {3: 'three', 4: 'four'}, 'dict2': {1: 'one', 2: 'two'}}
>>> dict_find_recursive(d, 'two')
'dict2'
>>> dict_find_recursive(d, 'five')
False
>>> d = {'dict1': {3: 'three', 4: 'four'}, 'dict2': {1: 'one', 2: 'two'},
'dict3': {1: {1:'five'}, 2: 'six'}}
>>> dict_find_recursive(d, 'five')
'dict3'
>>> dict_find_recursive(d, 'six')
'dict3'

如果你想反转一组任意嵌套的字典,递归生成器是你的 friend :

>>> def dict_flatten(d):
... if not isinstance(d, collections.Mapping):
... yield d
... else:
... for value in d:
... for item in dict_flatten(d[value]):
... yield item
...
>>> list(dict_flatten(d))
['three', 'four', 'five', 'six', 'one', 'two']

上面只是列出了字典中所有不是映射的值。然后,您可以将这些值中的每一个映射到一个键,如下所示:

>>> def reverse_nested_dict(d):
... for k in d:
... if not isinstance(d[k], collections.Mapping):
... yield (d[k], k)
... else:
... for item in dict_flatten(d[k]):
... yield (item, k)
...

这会生成一个可迭代的元组,因此不会丢失任何信息:

>>> for tup in reverse_nested_dict(d):
... print tup
...
('three', 'dict1')
('four', 'dict1')
('five', 'dict3')
('six', 'dict3')
('one', 'dict2')
('two', 'dict2')

如果您知道所有非映射值都是可哈希的——并且如果您知道它们是唯一的,或者如果您不关心冲突——那么只需将生成的元组传递给 dict():

>>> dict(reverse_nested_dict(d))
{'six': 'dict3', 'three': 'dict1', 'two': 'dict2', 'four': 'dict1',
'five': 'dict3', 'one': 'dict2'}

关于python - 在 python 中使用字典值获取字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8251876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com