检查python字典中是否存在数据

时间:2015-06-07 23:29:21

标签: python validation dictionary key

我有一个维护cd信息的平面文件数据库的程序。我正在尝试编写一个更新数据库的函数。在此功能中,我正在检查艺术家是否存在,如果是,则将相册名称附加到此艺术家,但由于某种原因,它不会看到我输入的艺术家已经存在。我确保我输入的内容与字典中的完全一样,但由于某种原因,python不会看到它存在。为什么会这样?我已经包含了示例输入以及python程序。任何帮助将不胜感激。

import sys

def add(data, block):
    artist = block[0]
    album = block[1]
    songs = block[2:]
    if artist in data:
        data[artist][album] = songs
    else:
        data[artist] = {album: songs}
    return data


def parseData():

    global data
    file='testdata.txt'
    data = {}
    with open(file) as f:
        block = []
        for line in f:
            line = line.strip()
            if line == '':
                data = add(data, block)
                block = []
            else:
                block.append(line)
        data = add(data, block)

    return data

def artistQry():

    global artists, usrChoiceArt, albums, usrChoiceAlb, usrArtist

    artists=sorted(data.keys())
    for i in range(0,len(artists)) :
        print str(i+1) + " : " + artists[i]



    usrChoiceArt = raw_input("Please choose an artist or enter q to quit:")

    if usrChoiceArt=='q' :
        print "Quitting Now"
        exit()
    else :
        albumQry()

def albumQry():

    global artists, usrChoiceArt, albums, usrChoiceAlb, usrArtist

    usrArtist=artists[int(usrChoiceArt)-1]
    albums=sorted(data[usrArtist].keys())

    for i in range(0,len(albums)) :
        print str(i+1) + " : " + albums[i]

    usrChoiceAlb=raw_input("Please choose an album or enter a to go back:")

    if usrChoiceAlb=="a":
        artistQry()
    else:
        trackQry()


def trackQry():

    global artists, usrChoiceArt, albums, usrChoiceAlb, usrArtist

    usrAlbum=albums[int(usrChoiceAlb)-1]
    tracks=data[usrArtist][usrAlbum]

    for i in range(0,len(tracks)) :
        print tracks[i]

    usrChoiceTrack=raw_input("Enter \"a\" to go back or \"q\" to quit:")

    if usrChoiceAlb=="q":
        print "Quitting Now"
        exit()
    elif usrChoiceTrack=="a":
        albumQry()
    else:
        print "Invalid Choice"
        trackQry()


def artistExist(Name):

    for i in range(0,len(data.keys())):

        if Name==data.keys()[i]:
            return True
        else:
            return False




def updData():

    artistName=raw_input("Please enter an artist name:")
    albumName=raw_input("Please enter an album name:")
    trackList=raw_input("Please enter the track list seperated by comma's:")

    if artistExist(artistName):
        data[artistName].append(albumName)
        print data[artistName]
    elif not artistExist(artistName):
        print "Quitting"
        exit()

if __name__ == '__main__':
data = parseData()


if sys.argv[1]=='-l':
    artistQry()
elif sys.argv[1]=='-a':
    updData()

输入数据:

Bob Dylan
1966 Blonde on Blonde
-Rainy Day Women #12 & 35
-Pledging My Time
-Visions of Johanna
-One of Us Must Know (Sooner or Later)
-I Want You
-Stuck Inside of Mobile with the Memphis Blues Again
-Leopard-Skin Pill-Box Hat
-Just Like a Woman
-Most Likely You Go Your Way (And I'll Go Mine)
-Temporary Like Achilles
-Absolutely Sweet Marie
-4th Time Around
-Obviously 5 Believers
-Sad Eyed Lady of the Lowlands

2 个答案:

答案 0 :(得分:1)

在函数artistExist中,在第一次迭代时返回False!相反,您必须等到所有迭代完成。

for i in range(0,len(data.keys())):

    if Name==data.keys()[i]:
        return True
return False

除了Padraic Cunningham says below之外,此处的elif也是多余的:

if artistExist(artistName):
    ...
elif not artistExist(artistName):
    ...

如果某些内容不是True,那么它只能是False。所以你真的应该

if artistExist(artistName):
    ...
else:
    ...

由于这个功能只是一个不必要的单行,所以更好的表达是

if artistName in data:
    ...
else:
    ...

答案 1 :(得分:1)

除了在循环中返回False过早返回,你做的工作太多了,你只需要使用return Name in data

def artistExist(Name):
    return Name in data # will return True or False with O(1) lookup

每次调用.keys时,您都在python2中创建一个列表,因此在最坏的情况下,您的查找实际上是二次的,而0(1)与简单的return Name in data相反。使用dict的很大一部分是有效的查找,你失去了调用.keys。如果你真的想迭代键,你只需要for key in data,不要调用.keys而不需要范围。