我有一张字典如图所示,我想知道如何编写内容来检查每个键的每个值,并检查它们是否满足特定条件,如8以上的值等。
http://i.imgur.com/qtfkK61.png
值为float,每个字典值的区域有多个值。
def main(): #defining main function
magList = [] #magnitude list of all together
regionList = [] #creating list to hold region names
wholeList = []
combinedList = []
with open("earthquakes.txt", "r") as eqList: #opens earthquake text file and gets the magnitudes
eqList.readline()
for line in eqList:
line = line.split()
magList.append(float(line[1])) #appends magnitude as float values in list
with open("earthquakes.txt", "r") as eqList2: #open file 2nd time for gathering the region name only
eqList2.readline()
for line in eqList2:
line = line.split()
line = line[0:7] + [" ".join(line[7:])] #takes whole line info and adds to list
wholeList.append(line)
greatMag = [] #creating lists for different category magnitudes
majorMag = []
strongMag = []
moderateMag = []
for x in magList: #conditions for seperating magnitude
if x >= 8:
greatMag.append(x)
elif 7 <= x <= 7.9:
majorMag.append(x)
elif 6 <= x <= 6.9:
strongMag.append(x)
elif 5 <= x <= 5.9:
moderateMag.append(x)
for line in wholeList: #takes only magnitude and region name from whole list
combinedList.append([line[7], line[1]])
infoDict = {} #creates dictionary
for key, val in combinedList: #makes one key per region and adds all values corresponding to the region
infoDict.setdefault(key, []).append(val)
print(infoDict)
for k, v in infoDict.items():
for i in v:
if i >= 8:
print("Great Magnitude:", i)
pass
if __name__ == "__main__": #runs main function
main()
答案 0 :(得分:0)
for k,v in d.items(): # iterate through key, value of dict 'd'
for i in v: # iterate to dict value which is a list
if i > 8: # your condition
# do something here
pass