检查 python 字典中是否存在数据
check existence of data in python dictionary
我有一个维护 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
在您的函数 artistExist
中,您 return 在第一次迭代时为 False!相反,您必须等到所有迭代都完成。
for i in range(0,len(data.keys())):
if Name==data.keys()[i]:
return True
return False
除了什么,这里的elif
也是多余的:
if artistExist(artistName):
...
elif not artistExist(artistName):
...
如果某件事不是真的,那么它只能是假的。所以你真的应该
if artistExist(artistName):
...
else:
...
而且由于该函数只是一个不必要的单行代码,所以更好的表达方式是
if artistName in data:
...
else:
...
除了通过在循环中返回 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 也不需要范围。
我有一个维护 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
在您的函数 artistExist
中,您 return 在第一次迭代时为 False!相反,您必须等到所有迭代都完成。
for i in range(0,len(data.keys())):
if Name==data.keys()[i]:
return True
return False
除了什么elif
也是多余的:
if artistExist(artistName):
...
elif not artistExist(artistName):
...
如果某件事不是真的,那么它只能是假的。所以你真的应该
if artistExist(artistName):
...
else:
...
而且由于该函数只是一个不必要的单行代码,所以更好的表达方式是
if artistName in data:
...
else:
...
除了通过在循环中返回 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 也不需要范围。