如何在python中访问字典的一部分?

时间:2013-08-28 06:16:54

标签: python dictionary

所以我有一个字典,其中包含与单词匹配的数字。 我希望能够根据用户输入的内容访问字典的一部分。

如何使用户输入一个号码,例如“2”,程序从字典中选择匹配“2”的项目并打印出来?或者如果用户输入“氢”(字典中的一个单词),则需要打印相应的数字(“1”)。

提前致谢

3 个答案:

答案 0 :(得分:1)

您可以创建两个dicts,一个将元素映射到其原子序号,另一个将原子序数映射到元素。这将在O(1)时间内运行。

>>> ele2atm = {'hydrogen':'2', 'oxygen':'8', 'carbon':'7'}
>>> atm2ele = {k:v for v, k in ele2atm.items()}
def get_value(key):
    try:
        return ele2atm[key]
    except KeyError:
        return atm2ele[key]


>>> get_value('8')
'oxygen'
>>> get_value('carbon')
'7'

或使用允许键和值之间进行一对一映射的bidict包。

示例:

>>> husbands2wives = bidict({'john': 'jackie'})
>>> husbands2wives['john'] # the forward mapping is just like with dict
'jackie'
>>> husbands2wives[:'jackie'] # use slice for the inverse mapping
'john'

答案 1 :(得分:0)

制作两个词典:

dict1 = {
    1: "baz",
    2: "bar",
    ...
}

dict2 = {
    "hydrogen": 1,
    "helium": 2,
    ...
}

input_ = raw_input("pick something: ")
try:
    print dict1[int(input_)]
except ValueError:
    print dict1[dict2[input_]]
except KeyError:
    print "Your desired key does not exist!"

答案 2 :(得分:0)

假设你的字典看起来像这样(因为你说数字到元素):

elements = {'2': 'Hydrogen', '8': 'Oxygen'}

你可以拥有这段代码:

user_input = '2'
for key,value in elements.items():
   if user_input == key:
      print value
   if user_input == value:
      print key

您可以将循环转换为方法:

def search_dictionary(user_input, haystack):
    for key,value in haystack.items():
        if user_input == key:
            return value
        if user_input == value:
            return key

然后像这样使用它:

user_input = raw_input('Please enter your search item: ')
elements = {'2': 'Hydrogen', '8': 'Oxygen'}
result = search_dictionary(user_input, elements)
if result:
    print("The result of your search is {0}".format(result))
else:
    print("Your search for {0} returned no results".format(user_input))