【问题标题】:Dictionary keys as dictionary字典键作为字典
【发布时间】:2015-04-19 20:10:54
【问题描述】:

问题

如何将字典的键用作字典名称,将先前的名称用作键?

这是一个类似的问题:
目前只找到了这个Python bidirectional mapping,涵盖了双向映射的基本功能。

虽然我不想找到值的键,但是像这样:

dict_one = { 'a': 123, 'b': 234 }
dict_two = { 'a': 567, 'b': 678 }
dict_one['a']
>> 123
dict_two['a']
>> 567
#... some magic (not simply defining a dict called 'a' though)
a['dict_one']
>> 123
a['dict_two']
>> 567

情况

我有许多存储不同对象常量的字典。每个对象都具有相同的属性(或者大多数对象都存在)。为了简化循环中常量的调用,两种描述的方式都是有用的。

【问题讨论】:

  • 我建议在此之前修改您的代码,这样一开始就不会出现这个问题meta.stackexchange.com/questions/66377/what-is-the-xy-problem
  • 只有 2 个字典吗?如果不是,您打算如何记住 dict 变量列表?
  • 您可以创建一个名为“a”的函数 (def a(dict_name):) 并使用 eval() 让您可以根据其名称访问 Dictionary 对象。这样就够了吗?
  • @sshashank124:你有什么建议? - 我想不出更好的方法来存储普通常量(见下文)。目前这主要是一个想法 - 但是你是对的,我要求y。 @BhargavRao:没有几个包含物理常数的字典(二维表,将来可能会扩展到更多)。调用 object['property']property['object'] 可以使处理同一对象的多个常量的函数更轻松,反之亦然。 @GordThompson:可能是一个解决方案,尽管它会将呼叫更改为a('object'),不是吗? (还有一件事要记住)
  • 是的,使用函数会调用a('dict_one') 而不是a['dict_one'],这就是我将建议作为评论而不是答案发布的原因。

标签: python dictionary mapping bidirectional


【解决方案1】:

您可以定义自己的继承自dict 的类来实现这一点,并覆盖__getitem__ 方法。但是这个解决方案也通过globals 字典添加变量,而不是我之前的其他人提到的推荐做法。

class mdict(dict):
    def __getitem__(self, item):
        self.normal = dict(self)
        return self.normal[str(globals()[item])]

dict_one = {'a': 123, 'b': 234}
dict_two = {'a': 567, 'b': 678}

lst = [dict_one, dict_two]

for item in lst:
    for k, v in item.iteritems():
        dd = globals().setdefault(k, mdict())
        dd[str(item)] = v


>>> print a['dict_one']
123
>>> print b['dict_one']
234
>>> print a['dict_two']
567
>>> print b['dict_two']
678

【讨论】:

    【解决方案2】:

    不应该使用以下解决方案,它修改了globals()(这种环境操作容易出错,应尽可能避免! ):

    dict_one = { 'a': 123, 'b': 234 }
    dict_two = { 'a': 567, 'b': 678 }
    
    output = {}
    for x in dict_one.keys():
        submap = output.get(x, {})
        submap["dict_one"] = dict_one[x]
        output[x] = submap
    
    for x in dict_two.keys():
        submap = output.get(x, {})
        submap["dict_two"] = dict_two[x]
        output[x] = submap
    
    
    # part 2
    globs = globals()
    
    for x in output:
        globs[x] = output[x]
    
    print a['dict_two'] # 567
    

    应该做的,只是简单地使用output作为抽象层(忽略前面代码sn-p的“第2部分”,而是使用):

    print output['a']['dict_one'] #123
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 2014-07-06
      • 2012-04-18
      相关资源
      最近更新 更多