美文网首页
dictionary字典

dictionary字典

作者: lalalasa | 来源:发表于2020-10-16 10:24 被阅读0次
  • 获取字典指定key的值

dict.get(key[, default])
VS
dict[key]

>>> dict = {"a":1,"b":2}

dict.get()

>>> dict.get("a")  # exist key
1
>>> dict.get("c","not exist")  # not exist key
'not exist'

dict[key]

>>> dict["c"]  # not exist key
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'

dict[key]遇到key不存在时报错,而get方法则可以设置默认值,特别是需要操作返回值时,get()方法更实用

  • 获取值或者插入键值对

setdefault(key[, default])

>>> dict = {"a":1,"b":2}
  • 不填写default(默认为None)
>>> dict.setdefault("a")  # exist key
1
>>> dict.setdefault("c")  # not exist key
>>> dict
{'a': 1, 'b': 2, 'c': None}  # dict add dict["c"]=None
  • 填写default
>>> dict.setdefault("c", -1)  # exist key, default = -1
>>> dict
{'a': 1, 'b': 2, 'c': None}  # no added
>>> dict.setdefault("d", -1)  # not exist key, default =-1
-1
>>> dict
{'a': 1, 'b': 2, 'c': None, 'd': -1}  # dict add dict["d"]=-1

如果dict存在该key,则返回key对应的Value
如果dict不存在该key,则插入key,Value=default,default默认为None

  • 插入或修改键值对

update([other])

>>> dict = {"a":1,"b":2}
>>> dict.update(b=1, c=2)
>>> dict
{'a': 1, 'b': 1, 'c': 2}
>>> dict.update({"c":4})
>>> dict
{'a': 1, 'b': 1, 'c': 4}

如果key存在dict,则修改key的对应值
如果key不存在dict,则dict新增该键值对
可简单理解为:有则修改,无则增加

  • 复制字典

d2 = d1

>>> d1
{'a': 1, 'b': 2}
>>> d2=d1
>>> d2["b"]=1
>>> d2
{'a': 1, 'b': 1}
>>> d1
{'a': 1, 'b': 1}

修改d2的值,d1的值也会变,原因是d2=d1是把d1的地址赋给了d2,两个变量指向同一个地址,因此d2修改了值,d1的值也会跟着变

d2 = d1.copy()

>>> d1
{'a': 1, 'b': 2}
>>> d2=d1.copy()
>>> d2["b"]=1
>>> d1
{'a': 1, 'b': 2}
>>> d2
{'a': 1, 'b': 1}
>>>

修改d2的值,d1的值不会跟着变

  • 合并两个dictionary

d | other
(New in version 3.9.)

>>> d1={'a': 1, 'b': 2}
>>> d2={'a': 1, 'b': 1, 'c': 4}
>>> d1 | d2
{'a': 1, 'b': 1, 'c': 4}

d |= other
New in version 3.9.

>>> d1={'a': 1, 'b': 2}
>>> d2={'a': 2, 'c': 2}
>>> d1 |= d2
>>> d1
{'a': 2, 'b': 2, 'c': 2}
>>> d2
{'a': 2, 'c': 2}

参考

相关文章

  • Swift第二篇(字典&集合)

    Swift字典:Dictionary Swift中的字典Dictionary与Foundation中的NSDict...

  • 字典&&列表&&元组

    {字典}&&[列表]&&(元组) 字典(dictionary) 创建dictionary:每个元素都是一个key-...

  • Python 字典(Dictionary)(1)

    Python 字典(Dictionary) 访问字典里的值

  • 字典-Dictionary

    这里要讲到的字典也是一种数据类型,你别理解成新华字典或者成语字典就Ok了,它其实是能够存储任何数据类型的对象......

  • 字典dictionary

    字典(dictionary) 字典可看作是键(key)与值(value)之间的一系列一一对应关系。 字典和列表相似...

  • dictionary字典

    获取字典指定key的值 dict.get(key[, default])VSdict[key] dict.get(...

  • Dictionary字典

    初始化 获取值 修改值 删除值 获取网址的key,value值

  • 字典(Dictionary)

    本文学习参考:http://www.runoob.com/python/python-dictionary.htm...

  • Swift字典

    ``` // 字典格式 // 字典名称 = {字典关键字}() var emptyDic = Dictionary...

  • YYModel 之个人Tips

    1.如何判断字典为空 if (!dictionary || dictionary == (id)kCFNull) ...

网友评论

      本文标题:dictionary字典

      本文链接:https://www.haomeiwen.com/subject/tnyopktx.html