蟒蛇;使用多个索引重新调整dictonary值

时间:2015-04-22 11:52:32

标签: python python-3.x dictionary

我试图根据值(foo)从字典中检索消息;我面临的问题是每条消息都有多个索引。当索引改变值时,证明难以检索相同的消息。我知道这可能没有多大意义,但我希望通过查看它将有用的代码。

foo=int(input('What is foo'))#foo is always 1 to 10
bar={10:'10/10',
 (8 or 9):'message1',
 (6 or 7):'message2',
 (4 or 5):'message3',
 (2 or 3):'message4',
 (0 or 1):'message5',
print(bar[foo])

这段代码是一个较大程序的一部分,我只能用这部分来解决。 Foo是预定的,因此用户不会在整个程序中输入它。我已经尝试了多个修复此问题,任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:6)

如果要使用单个整数作为键,可以使用math将每个键简化为单个唯一值,例如

bar = {5:'10/10',     # 10
       4:'message1',  # 9 or 8
       3:'message2',  # 7 or 6
       2:'message3',  # 5 or 4
       1:'message4',  # 3 or 2
       0:'message5'}  # 1 or 0

>>> foo = 7
>>> bar[foo // 2]
'message2'

答案 1 :(得分:1)

有很多方法可以解决这个问题。您可以多次放置一些字典值。 但是,如果您真的需要复合键,则可以将字典的键存储为2元组(10作为1元组)。然后,您可以先检索存储foo的密钥:

foo = int(input('What is foo'))
bar = {(10,):'10/10',
 (8, 9):'message1',
 (6, 7):'message2',
 (4, 5):'message3',
 (2, 3):'message4',
 (0, 1):'message5'}
print(bar[foo])

key = next(k for k in bar.keys() if foo in k)

然后检索值:

print(bar[key])

答案 2 :(得分:0)

您可以使用不同的键重复字典中的值。

bar={10:'10/10',
    9: 'message1',
    8:'message1',
    7:'message2',
    6:'message2',
    5:'message3',
    4:'message3',
    3:'message4',
    2:'message4',
    1:'message5',
    0:'message5',
    }

select = {9: 8,
          7: 6,
          5: 4,
          3: 2,
          1: 0}

foo = select.get(foo, foo) # If the value isn't found return the original value

bar={10:'10/10',
    8:'message1',
    6:'message2',
    4:'message3',
    2:'message4',
    0:'message5',
    }

 print(bar[foo])

或使用math.l

答案 3 :(得分:-1)

您已经有了一个可行的答案,因为您的特殊情况允许在检索上使用简单的算术表达式为您解决。但是,在一般情况下,解决方案是使用专门的映射类,它完全符合"多键"的目的。字典。

默认情况下,Python的stdlib中没有这样的数据结构,但Python Package Index上有几个不同的(和很好的)实现。一般情况下,您只需seacr pypi.python.org获取"多关键词典",从最高等级的词典中选择一个模块,然后将其添加到项目的要求中,或者直接安装" pip install"。

这样一个多密钥字典的想法并不难实现 - 只需实现为"可变映射"的接口(抽象基类)列出的适当方法。在一个完成这项工作的班级。一般来说"工作"将涉及一个或多个内部聚合词典。

例如:

from collections import MutableMapping
# (Collections.abc in Python 3.x)

class MDict(MutableMapping):
def __init__(self, *args, **kw):
    self._data = {}
    self._keys = {}
def __setitem__(self, key, value):
    if not hasattr(key, "__iter__") or not hasattr(key, "__len__"):
         key = (key,)
         self._keys[key] = key
    else:
         key = tuple(key)
    for component in key:
        self._keys[component] = key
    self._data[key] = value
def __getitem__(self, key):
    return self._data[self._keys[key]]
# Implement the other methods specified for MutableMapping:
# __delitem__, __iter__, __len__ 
# and other nice thigns to have (like def add_key(existing_key, newkey),
# delkey..