2014-12-04 57 views
0

我有一个字典,如图所示,我想知道我应该如何编写一些东西来检查每个键的每个值,并检查它们是否符合某个特定的条件像8以上的值等。检查Python中条件字典中的浮点值

http://i.imgur.com/qtfkK61.png

的值是浮子和有每个区域的字典值的多个值。

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

如果你选择从你的字典一些样本,并张贴在这里这将是有益的。 – 2014-12-04 05:15:40

+0

可能重复? http://stackoverflow.com/a/23862438/1174169。如果不是,那肯定是相关的。它使用字典理解过滤基于密钥的字典。此外,您希望*做什么*符合您的标准的数据? – cod3monk3y 2014-12-04 05:17:45

+0

添加了我的代码,你不能运行它,因为你们没有文本文件,只是看看我在末尾如何完成 – Lompang 2014-12-04 05:25:19

回答

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 
+0

如果i> = 8,那么“if i> = 8”会给我一个错误: TypeError:unorderable types:str()> = int()我遇到了同样的问题,在来这里之前。它不应该给我一个字符串比较错误,因为值是浮动不是字符串,但它无论如何。 – Lompang 2014-12-04 05:20:32

+0

@Lompang,仔细看看你的数据 - 你的* float *实际上是字符串,尝试'''如果float(i)> something:'' – wwii 2014-12-04 05:26:48

+0

我忘了你可以改变它为float当你做条件,这是有道理的,谢谢! – Lompang 2014-12-04 05:29:50