dict objects

今天来梳理一下Python dict 类型的知识点,特此申明下面信息均参考自公司培训课PPT Nagiza F. Samatova, NC State Univ. All rights,主要涉及到下面几个点:
在这里插入图片描述

  • Characteristics of the keys and dictionaries
  • How to createa dictionary object
  • How to retrieve dictionary items
  • How to updatea dictionary: add, delete, change items
  • How to iterateover dictionary items
  • How to query dictionary items

Characteristics of the keys and dictionaries

Dictionary is a mutable map of keys to values

Key is an immutable and unique object

Key is an immutable
key 不可能是list, set,因为他们是mutable,不可hash的

d1 = {
    
    ['script']:'java'}             # error unhashable type: 'list'
d2 = {
    
    {
    
    'A', 'B', 'C'}:'all grades'}  # error unhashable type: 'list'

key可以为bool, str, tuple,int, float

d_bool_key = {
    
    True : 5}
d_str_key = {
    
    'name': 'kelly'}
d_int_float_key = {
    
    9 : 'score', 3.7 : 'gpa'}
d_tuple_key = {
    
    ('first', 'last') : ('kelly', 'xia')}

Keys are UNIQUE取最后一个值

d1 = {
    
    'name':'kelly','name':'peter','name':'bob' }
d2 = {
    
    'first':'Smith', 'last':'Smith'}
print(d1)
print(d2)

# output:
{
    
    'name': 'bob'}
{
    
    'first': 'Smith', 'last': 'Smith'}

Keys can be of HETEROGENEOUS Types
d中的key有str和tuple

d = {
    
    'ssn: 555-55-5555':['jane', 'doe'], (16,17,18):'age group'}
print(d)

# output:
{
    
    'ssn: 555-55-5555': ['jane', 'doe'], (16, 17, 18): 'age group'}

How to Create a Dictionary Object?

empty

d = dict()
d = {}

d = {key : value}

d1 = {
    
    'key1':'value1', 'key2':'value2'}
d1

# output:
{
    
    'key1': 'value1', 'key2': 'value2'}

Not support: dict(‘key’:‘value’)

d = dict('key':'value')
d

# output:
 File "<ipython-input-640-efaed8bcc2a7>", line 1
    d = dict('key':'value')
                  ^
SyntaxError: invalid syntax

d=dict(key_name=value_object)

d2 = dict(key1='value1', key2='value2')
d2
# output:
{
    
    'key1': 'value1', 'key2': 'value2'}

d = dict([tuple, tuple])------via tuple list

d_2_tuple_list = dict([('script', 'python'), ('version', 3.8)])
d_1_tuple_list = dict([('script', 'python')])

print('d_2_tuple_list: {}'.format(d_2_tuple_list))
print('d_1_tuple_list: {}'.format(d_1_tuple_list))

# output:
d_2_tuple_list: {
    
    'script': 'python', 'version': 3.8}
d_1_tuple_list: {
    
    'script': 'python'}

Not support: d = dict(tuple)

d = dict(('a', 'b'))
d
# output:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-633-423a7c460802> in <module>
----> 1 d = dict(('a', 'b'))
      2 d

ValueError: dictionary update sequence element #0 has length 1; 2 is required

{tuple}----set

d_2_tuple = {
    
    ('script', 'python'), ('version', 3.8)}
d_1_tuple = {
    
    ('script', 'python')}

print('d_2_tuple: {}'.format(d_2_tuple))
print('d_1_tuple: {}'.format(d_1_tuple))

# output:
d_2_tuple: {
    
    ('script', 'python'), ('version', 3.8)}
d_1_tuple: {
    
    ('script', 'python')}

Not support: d = {[tuple, tuple]}

d = {
    
    [('script', 'python'), ('version', 3.8)]}
d

# output:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-612-db86a05588ef> in <module>
----> 1 d = {
    
    [('script', 'python'), ('version', 3.8)]}
      2 d

TypeError: unhashable type: 'list'

d=dict.fromkeys(key sequence, value)

keys = {
    
    'peter', 'bob', 'bruce'}
d1 = dict.fromkeys(keys, ['male', 'smoking', 30])
d2 = dict.fromkeys(keys, 30)
print('d1: {}'.format(d1))
print('d2: {}'.format(d2))

# output:
d1: {
    
    'bob': ['male', 'smoking', 30], 'peter': ['male', 'smoking', 30], 'bruce': ['male', 'smoking', 30]}
d2: {
    
    'bob': 30, 'peter': 30, 'bruce': 30}

d = dict(zip(collection1, collection2)

zip_3_3 = zip(['one', 'two', 'three'], [1,2,3])
zip_4_3 = zip(['one', 'two', 'three', 'four'], [1,2,3])
zip_3_4 = zip(['one', 'two', 'three'], [1,2,3,4])
d33 = dict(zip_3_3)
d43 = dict(zip_4_3)
d34 = dict(zip_3_4)
print('d33: {}'.format(d33))
print('d43: {}'.format(d43))
print('d34: {}'.format(d34))

只输出两个collection匹配成功的对数

# output:
d33: {
    
    'one': 1, 'two': 2, 'three': 3}
d43: {
    
    'one': 1, 'two': 2, 'three': 3}
d34: {
    
    'one': 1, 'two': 2, 'three': 3}

字典的推导式 创建

dic = {
    
    str(i) : i*2  for i in range(4)}
print(dic)

# output:
{
    
    '0': 0, '1': 2, '2': 4, '3': 6}

作业: 哈哈,巩固成果的时候到了。
在这里插入图片描述
在这里插入图片描述

ACCESS, RETRIEVE, UPDATE ITEMS

在这里插入图片描述
Access
key不存在会unknown key error

info_dict = {
    
    }  # do not miss this statement, or name 'info_dict' is not defined
key = 'name' 
info_dict [key] = 'kelly' 
print(info_dict [key])
print(info_dict ['unkonwnKey'])

# output:
kelly

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-644-de1581161396> in <module>
      3 info_dict [key] = 'kelly'
      4 print(info_dict [key])
----> 5 print(info_dict ['unkonwnKey'])

KeyError: 'unkonwnKey'
d = {
    
    'first': 'kelly', 'last':'xia'}
print('d.keys:\n{} '.format(d.keys()))
print('d.values:\n{} '.format(d.values()))
print('d.items:\n{} '.format(d.items()))
print('d.get("first"):\n{} '.format(d.get('first')))
print('d.get("phone"):\n{} '.format(d.get('phone')))
print('d.get("phone", "111-222-333-444"):\n{} '.format(d.get('phone', '111-222-333-444')))
print('d content:\n{}'.format(d))

注意:get(key, [default]) key:value是不是add到dict的

# output:
d.keys:
dict_keys(['first', 'last']) 
d.values:
dict_values(['kelly', 'xia']) 
d.items:
dict_items([('first', 'kelly'), ('last', 'xia')]) 
d.get("first"):
kelly 
d.get("phone"):
None 
d.get("phone", "111-222-333-444"):
111-222-333-444 
d content:
{
    
    'first': 'kelly', 'last': 'xia'} 

setdefault(key, default=None)

d = {
    
    'first': 'kelly', 'last':'xia'}

print('d.setdefault("first", "lydia"):\n{}'.format(d.setdefault('first', 'lydia')))
print('d.setdefault("age", 18):\n{}'.format(d.setdefault('age', 18)))
print('d.setdefault("cellphone"):\n{}'.format(d.setdefault('cellphone')))
print('afer setting:\n{}'.format(d))

如果key存在则返回value,如果key不存在,则设置默认None或value

d.setdefault("first", "lydia"):
kelly
d.setdefault("age", 18):
18
d.setdefault("cellphone"):
None
afer setting:
{
    
    'first': 'kelly', 'last': 'xia', 'age': 18, 'cellphone': None}

作业:
在这里插入图片描述

QUERYING BY-KEY: MEMBERSHIP CHECK

in operator

● to quickly check if a key is in a dictionary

d = {
    
    'script':'python'}
print('Is the key "script" in d:\n{}'.format('script' in d))
print('Is the key "version" in d:\n{}'.format('version' in d))
print('Is the value "python" in d:\n{}'.format('python' in d))

只应用到key上,对value无效

# output:
Is the key "script" in d:
True
Is the key "version" in d:
False
Is the value "python" in d:
False

ITERATING OVER DICTIONARY ITEMS

for key, item in d.items()

d = {
    
    'first':'kelly', 'last':'xia'}
for key, item in d.items():
    print('{}:{}'.format(key, item))
    
# output:
first:kelly
last:xia

for key in d.keys()

d = {
    
    'first':'kelly', 'last':'xia'}
for key in d.keys():
    print('{}:{}'.format(key, d[key]))

# output:
first:kelly
last:xia

for key in d

d = {
    
    'first':'kelly', 'last':'xia'}
for key in d:
    print('{}:{}'.format(key, d[key]))
    
# output:
first:kelly
last:xia

for value in d.values(), 但是不能访问key

d = {
    
    'first':'kelly', 'last':'xia'}
for value in d.values():
    print('{}'.format(value))

# output:
kelly
xia

Dictionaries: Other Methods

d = dict (name='John', age=20) 
Method Description Result
d.copy () Return copy, without modifying the original dictionary d.copy (name=‘John’, age=20)
d.clear () Remove all items {}
del d[key] Remove an items with a given key del d[name]
d.pop (key, [default]) Remove and return an element from a dictionary d.pop (‘age’)
d.update () Update the dictionary with elements from dictionary object d.update (d1)
d.fromkeys (sequence, [value]) Create a dictionary from sequence as keys w/ value provided keys = {‘1’, ‘2’, ‘3’} d.fromkeys (keys, 0)

dict.copy(d)

d = dict (name='John', age=20) 
print('original dict:\n id:{}\t content:{}'.format(id(d), d))
d_copy = dict.copy(d)
print('copy dict:\n id:{}\t content:{}'.format(id(d_copy), d_copy))

生成一个新的dict

# output:
original dict:
 id:2239127189312	 content:{
    
    'name': 'John', 'age': 20}
copy dict:
 id:2239126915072	 content:{
    
    'name': 'John', 'age': 20}

del d[key]—没有返回值

d = {
    
    'first':'kelly', 'last':'xia'}
del d['first']
d

# output:
{
    
    'last': 'xia'}

pop(key)-移除和返回value

d = {
    
    'first':'kelly', 'last':'xia'}
print('return d.pop("first"):{}'.format(d.pop('first')))
print('d content afer pop:{}'.format(d))

# output:
return d.pop("first"):kelly
d content afer pop:{
    
    'last': 'xia'}

d1.update(d2): key相同时会将d2的value替换d1的value,key不同时,会将d2的key value加入d1中

d1 = {
    
    'first':'kelly', 'last':'xia'}
d2 = {
    
    'first':'kelly', 'last':'wang', 'age':'18'}
d1.update(d2)
d1

# output:
{
    
    'first': 'kelly', 'last': 'wang', 'age': '18'}

作业:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wumingxiaoyao/article/details/109010119