零基础学Phyton

Python3基础入门 dict(字典)方法详述

2019-06-26  本文已影响22人  410ca74fb10e

写在前面

1. 概览

列出dict的所有不含_的方法

for l1 in dir(dict):
    if "_" not in l1:
        print((l1))
clear
copy
fromkeys
get
items
keys
pop
popitem
setdefault
update
values

1. clear方法

清空

dict1={'country':'china','province':'jiangsu','code':'025'}
dict1.clear()
dict1
{}

2. copy

复制

dict1={'country':'china','province':'jiangsu','code':'025'}
dict2=dict1.copy()
dict2
{'country': 'china', 'province': 'jiangsu', 'code': '025'}

3. fromkeys 创建新字典

从一个可迭代的对象来创建一个字典,对象的元素作为key,values可以为空,否则就是默认值

help(dict.fromkeys)
Help on built-in function fromkeys:

fromkeys(iterable, value=None, /) method of builtins.type instance
    Create a new dictionary with keys from iterable and values set to value.
#fromkeys() 方法使用给定的多个 key 创建字典,这些 key 对应的 value 默认都是 None;
#也可以额外传入一个参数作为默认的 value。该方法一般不会使用字典对象调用(没什么意义),通常会使用 dict 类直接调用。
dict1=dict.fromkeys(['a','b'])
print(dict1)
dict2=dict.fromkeys(('c','d'))
print(dict2)
dict3=dict.fromkeys('e','001')
print(dict3)
dict4=dict.fromkeys(['f','g','h'],'002')
print(dict4)
dict5=dict.fromkeys('helloworld',23)
print(dict5)
{'a': None, 'b': None}
{'c': None, 'd': None}
{'e': '001'}
{'f': '002', 'g': '002', 'h': '002'}
{'h': 23, 'e': 23, 'l': 23, 'o': 23, 'w': 23, 'r': 23, 'd': 23}

4. get

通过key来得到字典的值,若无则会返回none,跟下标访问有区别

help(dict.get)
Help on method_descriptor:

get(self, key, default=None, /)
    Return the value for key if key is in the dictionary, else default.
dict1={'country':'china','province':'jiangsu','code':'025'}
print(dict1.get('code'))
print(dict1.get('not'))#未知的键值就返回none
025
None

5. items,keys,values

items:键值对
keys:键
values:值

help(dict.items)
Help on method_descriptor:

items(...)
    D.items() -> a set-like object providing a view on D's items
help(dict.keys)
Help on method_descriptor:

keys(...)
    D.keys() -> a set-like object providing a view on D's keys
help(dict.values)
Help on method_descriptor:

values(...)
    D.values() -> an object providing a view on D's values
dict1={'country':'china','province':'jiangsu','code':'025'}
print('******Keys Here******')
for k in dict1.keys():
    print(k)

print('******Values Here******')
for v in dict1.values():
    print(v)

print('******Items Here******')
for k,v in dict1.items():
    print(k,v)
******Keys Here******
country
province
code
******Values Here******
china
jiangsu
025
******Items Here******
country china
province jiangsu
code 025

6. pop

弹出指定的键,返回值
如果key不存在,返回指定的d,否则抛出KeyError

help(dict.pop)
Help on method_descriptor:

pop(...)
    D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
    If key is not found, d is returned if given, otherwise KeyError is raised
dict1={'country':'china','province':'jiangsu','code':'025'}
dict1.pop('code')
print(dict1)
print(dict1.pop('province1','hello'))
print(dict1)
dict1.pop('province1')
{'country': 'china', 'province': 'jiangsu'}
hello
{'country': 'china', 'province': 'jiangsu'}



---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-11-2eeb48faedcc> in <module>
      4 print(dict1.pop('province1','hello'))
      5 print(dict1)
----> 6 dict1.pop('province1')


KeyError: 'province1'

7. popitem

  1. 移除键值对,如果字典为空则抛出KeyError
  2. 其实弹出"最后"一个键值对
help(dict.popitem)
Help on method_descriptor:

popitem(...)
    D.popitem() -> (k, v), remove and return some (key, value) pair as a
    2-tuple; but raise KeyError if D is empty.
#popitem
#popitem() 方法用于随机弹出字典中的一个 key-value 对
dict1={'country':'china','province':'jiangsu','code':'025'}
dict1.popitem()
print(dict1)
dict2={}
dict2.popitem()
{'country': 'china', 'province': 'jiangsu'}



---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-15-4992ebb4170b> in <module>
      5 print(dict1)
      6 dict2={}
----> 7 dict2.popitem()


KeyError: 'popitem(): dictionary is empty'

8. setdefault

help(dict.setdefault)
Help on method_descriptor:

setdefault(self, key, default=None, /)
    Insert key with a value of default if key is not in the dictionary.
    
    Return the value for key if key is in the dictionary, else default.
  1. 插入一个键,其值为给定的值,如果键在字典中不存在
  2. 如果键在字典中存在,则返回其对应的值

dict1={'nanjing':'025','suzhou':'0512'}
print(dict1.setdefault('suzhou','0511'))
print(dict1.setdefault('zhenjiang','0511'))
print(dict1)
0512
0511
{'nanjing': '025', 'suzhou': '0512', 'zhenjiang': '0511'}

9. update

help(dict.update)
Help on method_descriptor:

update(...)
    D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
    If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
    If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
    In either case, this is followed by: for k in F:  D[k] = F[k]
  1. 通过字典或可迭代的对象来更新字典
  2. 如果给出一个字典(或可迭代对象,存在keys方法),则更新D的对应的键值(不论存在与否,存在就覆盖,不存在就插入)
dict1={'country':'china','province':'jiangsu','code':'025'}
dict2={'country':'china','province1':'jiangsu','code':'026'}#已存在的则更新,不存在的插入
dict1.update(dict2)
print(dict1)

{'country': 'china', 'province': 'jiangsu', 'code': '026', 'province1': 'jiangsu'}
{'country': 'china', 'province': 'jiangsu', 'code': '026', 'province1': 'jiangsu', 'loc': 'river'}
{'country': 'china', 'province': 'jiangsu', 'code': '026', 'province1': 'jiangsu', 'loc': 'river', 'age': 18}
  1. 若果没有keys方法,那么...(不好解释看示例)
dict1={'country':'china','province':'jiangsu','code':'025'}
dict1.update(loc='river')
print(dict1)
dict1.update([('age',18)])
print(dict1)
{'country': 'china', 'province': 'jiangsu', 'code': '025', 'age': 18}

总结


十一个方法


查:keys、values、items、get
删:pop、popitem、clear
改:update
创建:setdefault 、fromkeys
其他:copy

上一篇下一篇

猜你喜欢

热点阅读