Python 2.7 如何在字典中搜索值后返回键
这应该是从.dat文件导入一个键和一个值(如john:fred等)到字典中。当程序运行时,它应该要求用户输入儿子的名字(字典中的值)并返回与之相关的密钥 例如,如果用户输入fred,它应该返回john 但问题是当调用它时,它会打印“none”而不是键。任何能帮忙的人都非常感激Python 2.7 如何在字典中搜索值后返回键,python-2.7,dictionary,return-value,key-value,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(","):
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
我建议简单地以另一种方式映射字典,这样您就可以正常使用它(通过键访问,而不是通过值访问)。毕竟,dict将键映射到值,而不是反过来:
>>> # 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'
这对我来说是新鲜事,所以你有没有可能解释得更详细一点。当然。特别是哪一部分?还是全部?全部。如果你可以给我发消息而不是做注释,那就好了。在示例代码中的注释中,每个人都可以看到它,怎么样?让我知道,如果这是足够的解释。