如何在字典中搜索值后返回密钥

时间:2014-04-16 17:52:26

标签: python-2.7 dictionary return-value key-value

这应该从.dat文件中导入字典中的键和值(即john:fred等)。当程序运行时,它应该要求用户输入儿子的名字(字典中的值)并返回与之关联的密钥。

例如,如果用户输入了fred,则应返回john

但问题是,当它被调用时,它会输出“none”而不是键。任何可以提供帮助的人都非常感激。

dataFile = open("names.dat", 'r')
myDict = { } 
for line in dataFile:
    for pair in line.strip(). split(","):
        k,v = pair. split(":")
    myDict[k.strip (":")] = v.strip()
    print(k, v)
dataFile.close() 
def findFather(myDict, lookUp): 
    for k, v in myDict.items ( ):
        for v in v:
            if lookUp in v:
                key = key[v]
                return key
lookUp = raw_input ("Enter a son's name: ")
print "The father you are looking for is ", findFather(myDict, lookUp)

文件是

john:fred, fred:bill, sam:tony, jim:william, william:mark, krager:holdyn, danny:brett, danny:issak, danny:jack, blasen:zade, david:dieter, adam:seth, seth:enos

问题是

(' seth', 'enos')
Enter a son's name: fred
The father you are looking for is  None

1 个答案:

答案 0 :(得分:0)

我建议简单地以另一种方式映射字典,以便您可以正常使用它(通过键访问,而不是按值访问)。毕竟,dicts将键映射到值,而不是相反:

>>> # Open "names.dat" for reading and call it namefile
>>> with open('names.dat', 'r') as namefile:
...   # read file contents to string and split on "comma space" as delimiter
...   name_pairs = namefile.read().split(', ')
...   # name_pairs is now a list like ['john:fred', 'fred:bill', 'sam:tony', ...]
>>> # file is automatically closed when we leave with statement
>>> fathers = {}
>>> for pair in name_pairs:  # for each pair like 'john:fred'
...   # split on colon, stripping any '\n' from the file from the right side
...   father, son = [name.rstrip('\n') for name in pair.split(':')]
...   # If pair = 'john:fred', now father is 'john' and son is 'fred'
...   fathers[son] = father  # which we enter into a dict named fathers
... 
>>> fathers['fred']  # now fathers['father_name'] maps to value 'son_name'
'john'