Dict KeyError for value in the dict

*爱你&永不变心* 提交于 2019-12-01 20:44:44
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.

You are attempting to search for a key that is an integer:

phoneNumberDictionary[int(line)]

However, your dictionary is defined with your phone numbers as strings.

'123456789'

Thus, the key with integer 123456789 doesn't exist.

Use integers as keys:

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

You have strings as keys but you need integers.

Not sure why you might be seeing that without more information - perhaps run in the interpreter and print out (a small) example output? In any event, something that I've found that helps in those cases is defaultdict Which will make a key with an object type of your choosing. It's a little off-base for this example, since you don't have homogeneous value-types (certainly not a requirement, but makes the most sense when using a defaultdict):

from collections import defaultdict
phoneNumberDict = defaultdict(lambda: defaultdict(int))
phoneNumber[int(vline)]["Frequency"] += 1

That said, for such a structure, I would think an object would be easier to keep track of things.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!