Dict KeyError获取字典中的值 [英] Dict KeyError for value in the dict

查看:199
本文介绍了Dict KeyError获取字典中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在字典中有一个字典:

I have a dict inside a dict:

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

这个想法是扫描由号码组成的通话清单,并与dict进行比较,从而增加每次找到匹配项的频率.

The idea is to scan a list of calls made by numbers and compare against the dict, increasing the frequency each time a match is found.

当我运行脚本时:

try:
phoneNumberDictionary[int(line)]['Frequency'] += 1
except KeyError:
phoneNumberDictionary[int(line)]['Frequency'] = 1

我收到错误消息:

KeyError: '18667209918'

(其中18667209918是当前正在搜索的号码)

(Where 18667209918 is the number that is currently being searched)

但是,当我打印字典并仅搜索该数字时,便可以立即找到它. 有什么想法吗?

Yet when I print the dict and just search for that number I can find it immediately. Any ideas?

推荐答案

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.

我认为您仍将从异常块中的语句中获得KeyError.从您的语句phoneNumberDictionary[int(line)]['Frequency'] = 1中,python假定您通过的键存在一个键值,并且它具有一个dictionary(其中Frequency作为其键之一).但是首先您有KeyError异常,因为您没有与18667209918

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.

这篇关于Dict KeyError获取字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆