Pergunta

This is supposed to import into a dictionary a key and a value (i.e. john: fred, etc..) from a .dat file. When the program is run, it is supposed to ask the user to enter the son's name (value in the dictionary) and return the key associated with it.

For example, if the user entered fred, it should return john

But the problem is when it is called, it prints "none" instead of the key. Any one that can help is very appreciated.

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)

the file is

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

the problem is

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

Solução

I would suggest simply mapping the dictionary the other way so you can use it normally (accessing by key, not by value). After all, dicts map keys to values, not the other way around:

>>> # 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'
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top