Dict KeyError for value in the dict

前端 未结 4 1886
Happy的楠姐
Happy的楠姐 2021-01-20 02:02

I have a dict inside a dict:

{
\'123456789\': {u\'PhoneOwner\': u\'Bob\', \'Frequency\': 0},
\'98765431\': {u\'PhoneOwner\': u\'Sarah\', \'Frequency\': 0},
         


        
4条回答
  •  青春惊慌失措
    2021-01-20 02:08

    dictionary =  {
         '123456789': {u'PhoneOwner': u'Bob', 'Frequency': 0},
         '98765431': {u'PhoneOwner': u'Sarah', 'Frequency': 0},
         }
    key_present = '123456789'
    
    try:
        dictionary[key_present]['Frequency'] += 1
    except KeyError:
        pass
    
    key_not_present = '12345'
    
    try:
        dictionary[key_not_present]['Frequency'] += 1
    except KeyError:
        dictionary[key_not_present] = {'Frequency': 1}
    
    print dictionary
    

    you have strings as keys in the dictionary but to access you are using an integer key.

    I think you will still get KeyError from the statement in the exception block. from your statement phoneNumberDictionary[int(line)]['Frequency'] = 1 python assumes that a key-value exists with the key you have passes and it has a dictionary with Frequency as one of its key. But you have got KeyError exception in the first place because you did not have a key matching 18667209918

    Therefore initialize the key-value pair of the outer dictionary properly.

提交回复
热议问题