因为最近在学机器学习算法,对于如何在dic里面添加dic有点不解,

如  myTree['no surfacing'][2] = 'maybe',表示在myTree这个dic的key 'no surfacing' 添加一个dic {2 : 'maybe'},  myTree['no surfacing'][3] = 'maybe' ,则表示{3 : 'maybe'}.

即[2]或[3]表示新加的dic的key,竟然不是表示下标(想想也对,dic不能用下标表示元素,是用key表示value,这么想的话就能理解了)。

所以可以总结得出dic里面加dic的方法:

字典名称[key][所要添加的dic的key] = 所要添加的value

为了验证该方法是否正确,做了一个实验

原来的dic为myTree={'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}

想在最后的dic添加dic {2 : 'maybe'},

代码为myTree['no surfacing'][1]['flippers'][2] = 'maybe',

添加后的结果为

{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes', 2: 'maybe'}}}}

用树来表示很清楚

原来的如下:(下面的代码都是在这个基础之上,而不是持续添加)

添加myTree['no surfacing'][2] = 'maybe'代码后

把[2]换做[3]后(证明[2]不是代表下标)

添加myTree['no surfacing'][1]['flippers'][2] = 'maybe'后

顺便当时在网上搜到了一篇文章,觉得对dic的知识点总结得不错,里面的挺多点在编写机器学习算法中都经常用到,所以在这里对dic的知识点做一下总结。

Python中的字典是python的一种数据结构,它的本质是key和value以及其对应关系的一种集合,一个key可以对应一个多个value。合理的使用字典能给我们编程带来很大的方便。

版本 python2.7

python3.0以上,print函数应为print(),不存在dict.iteritems()这个函数。

在python中写中文注释会报错,这时只要在头部加上# coding=gbk即可

#字典的添加、删除、修改操作
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
dict["w"] = "watermelon"
del(dict["a"])
dict["g"] = "grapefruit"
print dict.pop("b")
print dict
dict.clear()
print dict
#字典的遍历
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k in dict:
    print "dict[%s] =" % k,dict[k]
#字典items()的使用
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
#每个元素是一个key和value组成的元组,以列表的方式输出
print dict.items()
#调用items()实现字典的遍历
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for (k, v) in dict.items():
    print "dict[%s] =" % k, v
#调用iteritems()实现字典的遍历
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
print dict.iteritems()
for k, v in dict.iteritems():
    print "dict[%s] =" % k, v
for (k, v) in zip(dict.iterkeys(), dict.itervalues()):
    print "dict[%s] =" % k, v
   
#使用列表、字典作为字典的值
dict = {"a" : ("apple",), "bo" : {"b" : "banana", "o" : "orange"}, "g" : ["grape","grapefruit"]}
print dict["a"]
print dict["a"][0]
print dict["bo"]
print dict["bo"]["o"]
print dict["g"]
print dict["g"][1]
 
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
#输出key的列表
print dict.keys()
#输出value的列表
print dict.values()
#每个元素是一个key和value组成的元组,以列表的方式输出
print dict.items()
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
it = dict.iteritems()
print it
#字典中元素的获取方法
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
print dict
print dict.get("c", "apple")         
print dict.get("e", "apple")
#get()的等价语句
D = {"key1" : "value1", "key2" : "value2"}
if "key1" in D:
    print D["key1"]
else:
    print "None"
#字典的更新
dict = {"a" : "apple", "b" : "banana"}
print dict
dict2 = {"c" : "grape", "d" : "orange"}
dict.update(dict2)
print dict
#udpate()的等价语句
D = {"key1" : "value1", "key2" : "value2"}
E = {"key3" : "value3", "key4" : "value4"}
for k in E:
    D[k] = E[k]
print D
#字典E中含有字典D中的key
D = {"key1" : "value1", "key2" : "value2"}
E = {"key2" : "value3", "key4" : "value4"}
for k in E:
    D[k] = E[k]
print D
#设置默认值
dict = {}
dict.setdefault("a")
print dict
dict["a"] = "apple"
dict.setdefault("a","default")
print dict
#调用sorted()排序
dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}
print dict  
#按照key排序 
print sorted(dict.items(), key=lambda d: d[0])
#按照value排序 
print sorted(dict.items(), key=lambda d: d[1])
#字典的浅拷贝
dict = {"a" : "apple", "b" : "grape"}
dict2 = {"c" : "orange", "d" : "banana"}
dict2 = dict.copy()
print dict2

#字典的深拷贝
import copy
dict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}
dict2 = copy.deepcopy(dict)
dict3 = copy.copy(dict)
dict2["b"]["g"] = "orange"
print dict
dict3["b"]["g"] = "orange"
print dict

补充:
1 初始化
>>> d = dict(name='visaya', age=20)
>>> d = dict(zip(['name', 'age'], ['visaya', 20]))

#dict.fromkeys(listkeys, default=0) 把listkeys中的元素作为key均赋值为value,默认为0
>>> d = dict.fromkeys(['a', 'b'], 1)
>>> d
{'a': 1, 'b': 1}
2 字典视图和几何
dict.keys()类似信使可以进行交集和并集等集合操作(类似集合,因为不存在重复的项),但dict.values()不可以进行如上操作。

>>> k = d.keys()
>>> k
dict_keys(['a', 'b'])
>>> list(k)
['a', 'b']
>>> k | {'x': 3}
{'a', 'x', 'b'}
>>> k | {'x'}
{'a', 'x', 'b'}
>>> k | {'x', 'y'}
{'a', 'y', 'b', 'x'}
>>> k & {'x'}
set()
>>> v = d.values()
>>> v
dict_values([1, 2])
>>> v | {'x'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'dict_values' and 'set'
3 排序字典键
两种方法:
3.1 sort:
>>> Ks = list(d.keys())
>>> Ks.sort()
>>> for k in Ks:
...     print(k, d[k])
... 
a 1
b 2
3.2 sorted:
>>> for k in sorted(d.keys()):
...     print(k, d[k])
... 
a 1
b 2

3.3 注意
>>> for k in list(d.keys()).sort():
...     print(k, d[k])
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable

出错原因:
list.sort() list.append()函数都是对自身的操作,没有返回值,故需先将list(d.keys())的结果保存下来,在结果上进行sort()
4 常用函数
4.1 get()
D.get(k[, d])   => D[k] if k in D else d. d defaults to none.
4.2 pop()
D.pop(value[, d])   => Remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
4.3 udpate()
    D.update(E, **F) -> None.  Update D from dict/iterable E and F.
    If E has a .keys() method, does:     for k in E: D[k] = E[k]
    If E lacks .keys() method, does:     for (k, v) in E: D[k] = v
    In either case, this is followed by: for k in F: D[k] = F[k]

>>> d = dict(name='visaya', age=21)
>>> d1= {'age': 20, 'sex': 'male'}
>>> d2 = zip(['a', 'b'], [1, 2])

>>> d.update(d1)
>>> d
{'age': 20, 'name': 'visaya', 'sex': 'male'}
#for k in d1: d[k] = d1[k]

>>> d.update(d2)
>>> d
{'age': 20, 'name': 'visaya', 'sex': 'male'}
#for (k, v) in d2: d[k] = v
4.4 del()
del D[key]
4.5 clear()
4.6 copy()
Python中的dict
初始化
构造方法创建
Python代码  
d = dict()  
d = dict(name="nico", age=23)  
d = dict((['name', "nico"], ['age', 23]))  
 当然还有更方便,简单的
Python代码  
d = {}  
d = {"name":"nico", "age":23}  
 
 
遍历
通过对key的遍历,遍历整个dict
 
Python代码  
d = {"name":"nico", "age":23}  
for key in d:  
    print "key=%s, value=%s" % (key, d[key])  
      
for key in d.iterkeys():  
    print "key=%s, value=%s" % (key, d[key])  
      
for key in d.keys():  
    print "key=%s, value=%s" % (key, d[key])  
      
for key in iter(d):  
    print "key=%s, value=%s" % (key, d[key])  
      
for key,item in d.items():  
    print "key=%s, value=%s" % (key, item)  
 
 当然也可以直接遍历value
 
Python代码  
d = {"name":"nico", "age":23}  
for value in d.values():  
    print value  
      
for key,value in d.viewitems():  
    print "key=%s, value=%s" % (key, value)  
  
for value in d.viewvalues():  
    print "value=%s" % (value)  
这里values和viewvalues的区别
 
后者返回的是该字典的一个view对象,类似数据库中的view,当dict改变时,该view对象也跟着改变
 
常用方法
 
Python代码  
d = {"name":"nico", "age":23}  
d["name"] = "aaaa"  
d["address"] = "abcdefg...."  
print d   #{'age': 23, 'name': 'aaaa', 'address': 'abcdefg....'}  
 
 
获取dict值
Python代码  
print d["name"]               #nico  
print d.get("name")         #nico  
 
 如果key不在dict中,返回default,没有为None
Python代码  
print d.get("namex", "aaa")       #aaa  
print d.get("namex")                  #None  
 
排序sorted()
Python代码  
d = {"name":"nico", "age":23}  
for key in sorted(d):  
    print "key=%s, value=%s" % (key, d[key])  
#key=age, value=23  
#key=name, value=nico  
 
 
删除del
Python代码  
d = {"name":"nico", "age":23}  
Python代码  
del d["name"]  
#如果key不在dict中,抛出KeyError  
del d["names"]  
Python代码  
Traceback (most recent call last):  
  File "F:\workspace\project\pydev\src\ddd\ddddd.py", line 64, in <module>  
    del d["names"]  
KeyError: 'names'  
 
 
清空clear()
Python代码  
d = {"name":"nico", "age":23}  
d.clear()  
print d                                                    #{}  
 
copy()
Python代码  
d1 = d.copy()               #{'age': 23, 'name': 'nico'}  
#使用返回view对象  
d2 = d1.viewitems()    #dict_items([('age', 23), ('name', 'nico')])  
#修改字典d1,新增元素  
d1["cc"] = "aaaaaa"   
print d2                   
#dict_items([('cc', 'aaaaaa'), ('age', 23), ('name', 'nico')])  
 
 
pop(key[, default])
如果key在dict中,返回,不在返回default
Python代码  
#如果key在dict中,返回,不在返回default  
print d.pop("name", "niccco")                #nico  
print d.pop("namezzz", "niccco")           #niccco  
#key不在dict中,且default值也没有,抛出KeyError  
print d.pop("namezzz")                         #此处抛出KeyError  
 
popitem()
删除并返回dict中任意的一个(key,value)队,如果字典为空会抛出KeyError
Python代码  
d = {"name":"nico", "age":23}  
print d.popitem()       #('age', 23)  
print d.popitem()       #('name', 'nico')  
#此时字典d已为空  
print d.popitem()      #此处会抛出KeyError  
 
update([other])
将字典other中的元素加到dict中,key重复时将用other中的值覆盖
Python代码  
d = {"name":"nico", "age":23}  
d2 = {"name":"jack", "abcd":123}  
d.update(d2)  
print d     #{'abcd': 123, 'age': 23, 'name': 'jack'}

Python如何在dic(字典)里面添加dic(字典) 附dic基础知识相关推荐

  1. 无法将该对象添加到ldap服务器_LDAP 基础知识

    LDAP 基础知识 目录 简介 协议概览 目录结构 架构(Schema) 对象类(objectClass) 属性(Attribute) 条目(Entry) LDAP 中的数据 常用命令 启动和关闭: ...

  2. [Python从零到壹] 八.数据库之MySQL和Sqlite基础知识及操作万字详解

    欢迎大家来到"Python从零到壹",在这里我将分享约200篇Python系列文章,带大家一起去学习和玩耍,看看Python这个有趣的世界.所有文章都将结合案例.代码和作者的经验讲 ...

  3. python k线图和指标_期货k线图基础知识_一眼看清股市状况之用Python绘制K线图

    本文介绍关于一眼看清股市状况之用Python绘制K线图与cdp指标与期货大盘的分析周期选用有关吗?应该选用日线,还是60分钟.30分钟等时分线最为精确.与股票指标ovl是什么意思与股票均线怎么看与我想 ...

  4. python字典操作添加_Python字典常见操作实例小结【定义、添加、删除、遍历】

    本文实例总结了python字典常见操作.分享给大家供大家参考,具体如下: 简单的字典: 字典就是键值对key-value组合. #字典 键值对组合 alien_0 ={'color':'green', ...

  5. Python如何在Dataframe中新添加一列

    import pandas as pddata = pd.DataFrame(columns=['a','b'], data=[[1,2],[3,4]]) data dicts = {"hs ...

  6. python中如何将字典直接变成二维数组_python基础知识(列表、字典、二维数组)...

    记得改参数!!! (1)简述列表(list)结构的特点. List(列表) List的元素以线性方式存储,可以存放重复对象,List主要有以下两个实现类: ArrayList : 长度可变的数组,可以 ...

  7. Excel导出改造_只填写字典类型_就可以自动对应导出_字典类添加获取字典值方法---SpringCloud Alibaba_若依微服务框架改造---工作笔记013

    若依微服务框架,默认的excel导出功能,导出字段的时候需要: 在实体类上自己写上,比如 在属性上写上字典值,这里需要自己手动的写上 用readConverterExp写上. 但是如果,比如碰到,全国 ...

  8. 运行python程序的两种方式交互式和文件式_Python基础知识2

    运行Python程序的两种方式 小白学习,如有错误欢迎指点 一.每位小白写的第一个Python程序 1.运行Python程序的两种方式 1.1 交互式模式(即时对话) 打开cmd,打开Python解释 ...

  9. 【Python数据挖掘课程】六.Numpy、Pandas和Matplotlib包基础知识

    前面几篇文章采用的案例的方法进行介绍的,这篇文章主要介绍Python常用的扩展包,同时结合数据挖掘相关知识介绍该包具体的用法,主要介绍Numpy.Pandas和Matplotlib三个包.目录:   ...

  10. python循环数组判断,python的数据类型、数组、条件判断、循环的基础知识

    一.数据类型 最常见的数据类型有:整型(int),浮点型(float),字符串(strs).例如: #整型 a=8   #浮点型 b=8.0  #字符串 c='hello world'. 数据类型的转 ...

最新文章

  1. 优秀的 Java 项目代码都是如何分层的?
  2. Linux安装图解全过程(Linux Text文本界面安装)
  3. python 数据库的Connection、Cursor两大对象
  4. Oracle Index
  5. 【C 语言】字符串操作 ( 使用 数组下标 操作字符串 | 使用 char * 指针 操作字符串 )
  6. 蓝桥杯——机器人行走
  7. listview 刷新结束 监听_Flutter 开发从 0 到 1(四)ListView 下拉加载和加载更多
  8. php递归实现冒泡排序,排序算法之PHP版快速排序、冒泡排序
  9. 改善你的生活品质,可以从一块小小的单片机开始
  10. C语言例题9:冒泡排序
  11. 通过dSYM文件分析crash日志
  12. HaaS低功耗IP Camera解决方案
  13. log4j2漏洞复现
  14. 一文读懂NFT(非同质化通证)
  15. CocosStudio(八)AtlasLabel数字标签、BitmapLabel自定义字体、Label文本框
  16. 快手极速版源码 - autojs 自阅
  17. 鸿蒙系统宣传标语,有多项新功能加持,搭载鸿蒙系统的华为手表WATCH 3来了!...
  18. python 中关键字 global 的用法
  19. getchar ,putchar,gets,puts的辨析
  20. 服务器中毒怎么找出病毒源文件,电脑中毒后怎样查找出在哪个文件夹

热门文章

  1. 根据屏幕手指划痕解图案锁屏
  2. 【vue3+ts后台管理】用户列表查询、编辑
  3. flutter纵向滚动嵌套横向滚动
  4. 【回归预测】基于粒子滤波实现锂离子电池寿命预测附matlab代码
  5. 面对Spring Boot 3最低支持Java17如洪水猛兽袭来,何去何从
  6. 数据结构——【队列】知识介绍+基本操作代码
  7. 聚合群控系统能做的网赚项目有哪些?
  8. 2 软件测试生命周期,软测试常见面试题-简述一下软件缺陷的生命周期
  9. FastAPI 对MySQL 数据库的操作(win64)
  10. PhpSpreadsheet处理Excel 导入、导出并设置样式