在python中使用dict值获取dict键 [英] getting dict key using dict value in python

查看:134
本文介绍了在python中使用dict值获取dict键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My question is: How can I get a dictionary key using a dictionary value?

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

我想获得 dict2 键$ key $ 2 $ / code>的键。

I want to get dict2 the key of the key of two.

谢谢。

推荐答案

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

Here's a recursive solution that can handle arbitrarily nested dictionaries:

>>> 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 被用作code关键;一个完全一般的解决方案将使用唯一的前哨 object()来表示虚伪。)

It's not as efficient in the long run as a "reverse dictionary," but if you aren't doing such reverse searches frequently, it probably doesn't matter. (Note that you have to explicitly compare the result of dict_find_recursive(d[k], target) to False because otherwise falsy keys like '' cause the search to fail. In fact, even this version fails if False is used as a key; a fully general solution would use a unique sentinel object() to indicate falseness.)

几个用法示例:

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

任意嵌套的字典集,递归生成器是您的朋友:

If you want to reverse an arbitrarily nested set of dictionaries, recursive generators are your 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']

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

The above simply lists all the values in the dictionary that aren't mappings. You can then map each of those values to a key like so:

>>> 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)
... 

这会生成一个可迭代的元组,所以没有信息丢失:

This generates a iterable of tuples, so no information is lost:

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

如果你知道所有的非映射值都是可哈希的 - 如果你知道或者如果不关心碰撞,那么只需将结果元组传递给 dict()

If you know that all your non-mapping values are hashable -- and if you know they are unique, or if you don't care about collisions -- then just pass the resulting tuples to dict():

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

这篇关于在python中使用dict值获取dict键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆