count.pop(tempKey) 这句不对
keyerror什么意思python python报keyerror
keyerror什么意思python python报keyerror
你把count清空了print(s) #{200,10,300,20,400,30,80,40}
把"count.pop(tempKey)"这一句去掉就应该OK了
di#源 公众号ct.pop的用法如下
pop(key[, default])
If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
seq = ['a', 'hello', 'hello', 'hello', 'hello', 'hello', 'hello', 'world', 'z', 'world', 'world', 'z']
temp = [(a, seq.count(a)) for a in keySet]
temp.sort(lambda x,y: cmp(x[1],y[1]))
在Python中,字典(dictionary)提供了一个pop()方法,该方法可以删除特定的键(key)并返回其对应的值(value)。如果你只想删除键而不需要值,你可以使用pop()方法。这些方法都是在dict数据类型上定义的。
from EventMar import以下是如何使用这些方法的示例:
python
# 创建一个字典
print(f"After popping {key_to_remove}, the removed value is: {removed_value}")
print(f"The remaining dictionary is: {my_dict}")
# 使用pop()随机删除一个键并获取它的值
removed_ = my_dict.pop()
print(f"After popping------------------------------ an , the removed is: {removed_}")
print(f"The remaining dictionary is: {my_dict}")
在上面的代码中,pop()和pop()都会删除字典中的元素。如果你试图删除一个不存在的键,pop()会抛出一个KeyError异常。如果你想要避免这个异常,你可以先使用in关键字检查键是否在字典中,例如:
python
key_to_remove = 'd'
if key_to_remove in my_dict:
else:
print(f"{key_to_remove} is not in the dictionary")
在这个例子中,如果键'd'在字典中,它会被删除并打印出其值。如果键'd'不在字典中,将打印一条消息表示该键不在字典中。
这些程序是你自己写的吗?
import pickle as presult = apiOcr.BasicGeneral(image)
ntMar.Start()根据我自己的主观认识,大概是通过 requests 之类的去调用百度的识别图的 api,参数可能有认证码和content。返回值可能是 json
mywords=result["words_result"]
KeyError: 'words_result'
表示 json 或者字典中没有 words_result 字段,你自己 print 看看 result 里面都返回了些什么就知道了。
附:image 没有 close,请 close 或使用 with
# 系统模块
from Queue import Queue, Empty
from threading import
########################################################################
class EventMar:
#----------------------------------------------------------------------
def __init__(self):
"""初始化管理器"""
# 对象列表
self.__ntQueue = Queue()
# 管理器开关
self.__active = False
# 处理线程
self.__thread = Thread(target = self.__Run)
# 这里的__handlers是一个字典,用来保存对应的的响应函数
# 其中每个键对应的值是一个列表,列表中保存了对该的响应函数,一对多
self.__handlers = {}
#----------------------------------------------------------------------
def __Run(self):
"""引擎运行"""
while self.__active == True:
# 获取的阻塞时间设为1秒
nt = self.__ntQueue.get(block = True, timeout = 1)
self.__EventProcess(nt)
except Empty:
pass
#----------------------------------------------------------------------
def __EventProcess(self, nt):
"""处理"""
if nt.type_ in self.__handlers:
# 若存在,则按顺序将传递给处理函数执行
for handler in self.__handlers[nt.type_]:
handler(nt)
#----------------------------------------------------------------------
def Start(self):
# 将管理器设为启动
self.__active = True
# 启动处理线程
self.__thread.start()
#----------------------------------------------------------------------
def Stop(self):
"""停止"""
# 将管理器设为停止
self.__active = False
# 等待处理线程退出
self.__thread.join()
#----------------------------------------------------------------------
def AddEventListener(self, type_, handler):
"""绑定和处理函数"""
# 尝试获取该类型对应的处理函数列表,若无则创建
handlerList = self.__handlers[type_]
except KeyError:
handlerList = []
self.__handlers[type_] = handlerList
# 若要注册的处理器不在该的处理器列表中,则注册该
if handler not in handlerList:
handlerList.append(handler)
#----------------------------------------------------------------------
def RemoveEventListener(self, type_, handler):
"""移除的处理函数"""
#读者自己试着实现
#----------------------------------------------------------------------
def SendEvent(self, nt):
"""发送,向队列中存入"""
self.__ntQueue.put(nt)
########################################################################
"""对象"""
class Event:
def __init__(self, type_=None):
self.type_ = type_ # 类型
self.dict = {} # 字典用于保存具体的数据测试代码 # encoding: UTF-8
import sys
from threading import
#名称 新文章
_ARTICAL = "Event_Artical"
class PublicAccounts:
def __init__(self,ntMar):
self.__ntMar = ntMar
def WriteNewArtical(self):
#对象,写了新文章
nt = Event(type_=_ARTICAL)
nt.dict["artical"] = u'如何写出更优雅的代码
'#发送
print u'公众号发送新文章
'# 者
class Listener:
self.__userdict = {'Al': '2341', 'B': '02', 'Cecil': '3258'}name = username
#的处理函数 读文章
def ReadArtical(self,nt):
print(u'%s 收到新文章' % self.__username)
print(u'正在阅读新文章内容:%s' % nt.dict["artical"])
"""测试函数""removed_value = my_dict.pop(key_to_remove)"
#--------------------------------------------------------------------
def test():
listner1 = Listener("thinkroom") #者1
ntMar = EventMar()
#绑定和响应函数(新文章)
ntMar.AddEventListener(_ARTICAL, listner1.ReadArtical)
ntMar.AddEventListener(_ARTICAL, listner2.ReadArtical)
timer = Timer(2, publicAcc.WriteNewArtical)
timer.start()
if __name__ == '__main__':
竟然一分都没有-。-!
你这个字典每次程序运行就重新加载,当然啥都米了。。
pickself.__ntMar.SendEvent(nt)le这个模块是让你把字典存在file中,也就是硬盘文件中的固定文件里,你是怎么用的啊?
p.dump('yourdict','yourfile')#将字典存入文件中
p.load('yourfile')#将字典从文件中取出
------------------
这样都搞不定的话,你得+点分,我再讲。。喝口水先
++++++++++++++++++++++++++++
哎,可怜的娃啊。。。
还得手把手教。。
你先另外重开个程序,这样写:
str={"朋友":"friend",
"File "
", line 1, in
"男人":"man",
}p.dump(str,open('D:/temp.dict','w'))
运行一遍,你看看你的D盘下是不是多了个temp.dict文件,有的话:
在你的程序中把
str={"朋友":"friend",
"一":"one",
"男人":"man",
}这句改成:
str = p.load(open('D:/temp.dict','r'))
在while结束后+一句:
p.dump(str,open('D:/temp.dict','w'))
搞定。。。。
dict全称dictionary,使用键-值(key-value)存储,具有极快的查找速度。
举个例子,设要根据同学的名字查找对应的成绩,如果用list实现,需要两个list:
names = ['Michael', 'Bob', 'Tracy']
scores = [95, 75, 85]
给定一个名字,要查找对应的成绩,就先要在names中找到对应的位置,再从scores取出对应的成绩,list越长,耗时越长。
如果用dict实现,只需要一个“名字”-“成"""启动"""绩”的对照表,直接根据名字查找成绩,无论这个表有多大,查找速度都不会变慢。用Python写一个dict如下:
>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95
把数据放入dict的方法,除了初始化时指定外,还可以通过key放入:
>>> d['Adam'] = 67
>>> d['Adam']
67
由于一个key只能对应一个value,所以,多次对一个key放入value,后面的值会把前面的值冲掉:
>>> d['Jack'] = 90
>>> d['Jack']
90
>>> d['Jack'] = 88
>>> d['Jack']
88
如果key不存在,dict就会报错:
>>> d['Thomas']
File "", line 1, in KeyError: 'Thomas'
要避免key不存在的错误,有两种办法,一是通过in判断key是否存在:
>>> 'Thomas' in dFalse
二是通过dict提供的get()方法,如果key不存也可如此创建字典在,可以返回None,或者自己指定的value:
>>> d.get('Thomas')
>>> d.get('Thomas', -1)
-1
要删除一个key,用pop(key)方法,对应的value也会从dict中删除:
>>> d.pop('Bob')
def __init__(self,username):75
1.传统的文字表达式:
>>> d={'name':'Allen','age':21,'gender':'male'}
如果你可以事先拼出整个字典,这种方显示删除一个字典用del命令,如下实例:式是很方便的。
2.动态分配键值:
>>> d={}
>>> d['name']='Allen'
>>> d['age']=21
>>> d['gender']='male'
如果你需要一次动态地建立一个字典的一个字段,那么这种方式比较合适。
字典与列表不同,不能通过偏移量进行,只能通过键来读取或赋值,所以也可以这样为字典赋值,当然访问不存在的键会报错:
>>> d[1]='abcd'
{1: 'abcd', 'age': 21, 'name': 'Allen', 'gender': 'male'}
>>> d[2]
KeyError: 212345678
3.字典键值表
>>> c = dict(name='Allen', age=14, gender='male')
>>> c
{'gender': 'male', 'name': 'Allen', 'age': 14}
因为这种形式语法简单,不易出错,所以非常流行。
这种形式所需的代码比常量少,但是键必须都是字符串才行,所以下列代码会报错:
>>> c = dict(name='Allen', age=14, gender='male', 1='abcd')
4.字典键值元组表
>>> e=dict([('name','Allen'),('age',21),('gender','male')])
>>> e
5.所有键的值都相同或者赋予初始值:
>>> f=dict.fromkeys(['height','weight'],'normal')
>>> f
{'weight': 'normal', 'height': 'normal'}
Python的是c# encoding: UTF-8ollections
里面有元祖,列表,,字典
tuple list set dict
原组是不能修改的列表
是没有重复的列表
字典是键值对
dict[]和dict.get两个方法的区别吧
二、访问字典里的值dict[k>>> dey]:
当key不存在的时候,会抛出异常
当key不存在的时候,不会抛出异常,而且会返回默认值
下面我们来具体看下字典的用法:
一、创建字典
字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下:
也可如此创建字典:
dict1 = { 'abc': 456 };dict2 = { 'abc': 123, 98.6: 37 };
注意:
键必须,但值则不必。
值可以取任何数据类型,但必须是不可变的,如字符串,数或元组。
把相应的键放入熟悉的方括弧,如下实例:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print "dict['Name']: ", dict['Name'];print "dict['Age']: ", dict['Age'];#以上实例输出结果: #dict['Name']: Zara#dict['Age']: 7
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print "dict['Al']: ", dict['Al']; #以上实例输出结果: #dict['Zara']:#Traceback (most recent call last):# File "test.py", line 4, in
三、修改字典
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:
四、删除字典元素
五、字典键的特性
字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。
publicAcc = PublicAccounts(ntMar)两个重要的点需要记住:
1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}; print "dict['Name']: ", dict['Name'];#以上实例输出结果:#dict['Name']: Manni
2)键必须不可变,所以可以用数,字符串或元组充当,所以用列表就不行,如下实例:
#!/usr/bin/python dict = {['Name']: 'Zara', 'Age': 7}; print "dict['Name']: ", dict['Name'];#以上实例输出结果: #Traceback (most recent call last):# File "test.py", line 3, in
六、字典内置函数&方法
1、cmp(dict1, dict2):比较两个字典元素。
2、len(dict):计算字典元素个数,即键的总数。
3、str(dict):输出字典可打印的字符串表示。
4、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。
Python字典包含了以下内置方法:
1、radiansdict.clear():删除字典内所有元素
2、radiansdict.copy():返回一个字典的浅
3、radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4、radiansdict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值
5、radiansdict.has_key(key):如果键在字典dict里返回true,否则返回false
# 检查是否存在对该进行的处理函数6、radiansdict.s():以列表返回可遍历的(键, 值) 元组数组
7、radiansdict.keys():以列表返回一个字典所有的键
8、radiansdict.setdefault(key, default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
9、radiansdict.update(dict2):把字典dict2的键/值对更新到dict里
10、radiansdict.values():以列表返回字典中的所有值
版权声明:本文内容由互联。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发 836084111@qq.com 邮箱删除。