如何在python中计算字典中的文章

时间:2014-04-17 00:57:48

标签: python-2.7 dictionary count key-value

我想要计算字典中的项目数。当用户输入要搜索的值时,它会找到值的键,然后返回它之前的下一个键。即({john:fred,fred:bill})

如果用户输入john,它将返回账单,反之亦然。

我的代码是:

myDict = {}
with open("names.dat") as f:
    for line in f:
        for pair in line.strip ().split(', '):
            i = 0
            x = 0
            (key, val) = pair.split (":")
            myDict[key.strip(":")] = val
            print "father: ", key , " son: ", val


def findFather (myDict, lookUp):
    father = ""
    for key, val in myDict.iteritems( ):
        if val == lookUp:
            key = key
            father = key
            return father
lookUp = raw_input ("Enter a son's name: ")
print 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

1 个答案:

答案 0 :(得分:0)

根据您的评论,您试图在数据库中找到一个人的祖父,将人们映射到他们的父亲身上:

def read_db(fname):
    with open(fname) as f:
        return dict(pair.split(":")
                    for pair in line.strip().split(", ")
                    for line in f)


def grandfather(db, person):
    return db.get(db.get(person))  # same as db[db[person]] except returns None when no match found instead of error


def main():
    DB = read_db("names.dat")

    print "\n".join("father: %s son: %s" % pair for pair in DB)

    person = raw_input("Enter a son's name: ")
    print grandfather(DB, person)  # prints None if no father or no grandfather found


main()

如您所见,DB是整个计划中唯一需要的变量(person中的main也可以内联);在您的问题中,您的代码包含大量噪音,这些噪音绝对不会阻止您理解您的代码并使您的问题看起来非常不整洁。因此,下次在Stack Overflow上提出问题时,请尝试清理所有内容。另外,请查看全能的PEP8