【问题标题】:how to check if value exist in dictionary如何检查字典中是否存在值
【发布时间】:2020-08-25 15:09:32
【问题描述】:

以下是我的字典。如何检查给定值是否在字典中。例如,如果用户输入一个数字 129,那么如何检查该数字是否存在于键 AB 中?

studentData = {
          'A': [127, 104],
          'B': [128,  204, 205, 118]
       }

if studID <= 0 :
    print ('Invalid id. Student id must be positive')
    studID = int(input('Enter student id: '))
elif studID in studentData.values() == True:   # how to check if input exist?
    print (f'fail')        
else:
    studentData[modCode].append(int(studID))
    print ("complete")     
    break 

【问题讨论】:

  • if number in studentData['A'] or number in studentData['B']?
  • if any(studID in vals for vals in studentData.values())
  • studentData.values() 给出了一个(整数列表)列表。您需要检查studID 是否在(int 列表)的每个 中。您目前只需检查studID 是否在列表列表中(显然不是,因为studID 是一个不在列表列表中的int
  • @GreenCloakGuy,“你需要这样做,这就是为什么”比“这样做”更有帮助。
  • @GreenCloakGuy 谢谢你是对的 :))

标签: python dictionary


【解决方案1】:

假设如下:

studentData = {
    'A': [127, 130, 123, 210, 109, 128, 204, 206, 111, 129, 103, 116, 112, 209, 122, 202, 121, 101, 113, 104],
    'B': [128, 206, 101, 111, 127, 119, 113, 207, 117, 204, 106, 123, 103, 105, 205, 118]
}

modCode 包含'A''B'

if studID <= 0 :
    print ('Invalid id. Student id must be positive')
    studID = int(input('Enter student id: '))
elif studID in studentData[modCode]:   # how to check if input exist?
    print (f'Add to Enrolment operation failed. Student is already enrolled in {modCode}')        
else:
    studentData[modCode].append(studID)
    print ("Add to Enrolment operation has successfully completed")

【讨论】:

    【解决方案2】:

    你可以很容易地用“in”语句检查键值内的值

    for key in ['A', 'B']:
        print(studID in studentData[key])
             
    

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 2012-03-27
      • 2016-03-20
      • 2021-11-30
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      相关资源
      最近更新 更多