Python:Dictionary用法与示例速查整理

发布时间:2023-09-05 10:30

 相关资料地址:gto76/python-cheatsheet: Comprehensive Python Cheatsheet (github.com)


目录

一、Dict的创建

1、dict的用法示例

(1)使用dict通过带参方式创建

(2)使用dict通过zip拼接方式来创建

2、dict.fromkeys的用法示例(生成所有键的值均为value的字典)

3、defaultdict的用法示例

二、Dict的元素添加、修改、删除        

1、Dict的元素添加与修改

(1)直接添加与直接修改

(2)update的用法示例(使用update添加与修改)

2、Dict元素的删除 

(1)pop的用法示例

三、Dict的元素查询

1、keys的用法示例(查询所有键)

2、values的用法示例(查询所有值)

3、items的用法示例

4、get的用法示例(根据key来获取值)

5、setdefault的用法示例

四、Dict的其他用法示例

1、生成相同value值的key集合

2、筛选对应key的键值对到新的字典中


一、Dict的创建

示例:

 = dict()                     # Creates a dict from coll. of key-value pairs.
 = dict(zip(keys, values))                # Creates a dict from two collections.
 = dict.fromkeys(keys [, value])          # Creates a dict from collection of keys.
 = collections.defaultdict()        # Creates a dict with default value of type.
 = collections.defaultdict(lambda: 1)     # Creates a dict with default value 1.

用法:

1、dict的用法示例

(1)使用dict通过带参方式创建

#  = dict()                     # Creates a dict from coll. of key-value pairs.

# dict的通过带参方式创建
my_dict = dict(a=1, b=2)
print(my_dict)
# {'a': 1, 'b': 2}

(2)使用dict通过zip拼接方式来创建

#  = dict(zip(keys, values))                # Creates a dict from two collections.

# dict通过zip拼接来创建
keys = [0, 1, 2, 3]
values = ['a', 'b', 'c', 'd']
my_dict = dict(zip(keys, values))
print(my_dict)
# {0: 'a', 1: 'b', 2: 'c', 3: 'd'}

2、dict.fromkeys的用法示例(生成所有键的值均为value的字典)

#  = dict.fromkeys(keys [, value])          # Creates a dict from collection of keys.

# 使用fromkeys创建默认值为value的字典
keys = [0, 1, 2, 3]
value = 'a'
my_dict = dict.fromkeys(keys, value)
print(my_dict)
# {0: 'a', 1: 'a', 2: 'a', 3: 'a'}

 3、defaultdict的用法示例

查询不存在key的时候

  • dict:返回KeyError
  • defaultdict:返回元素类型
# defaultdict的用法
import collections

my_list = [1 ,2 ,3 ,4 ,5]
my_dict1 = collections.defaultdict(int)
my_dict2 = collections.defaultdict(list)
my_dict3 = collections.defaultdict(str)
my_dict4 = collections.defaultdict(set)

print(my_dict1)
print(my_dict2)
print(my_dict3)
print(my_dict4)
# defaultdict(, {})
# defaultdict(, {})
# defaultdict(, {})
# defaultdict(, {})


# 查询不存在的key
print(my_dict1[1])
print(my_dict2[1])
print(my_dict3[1])
print(my_dict4[1])
# 0
# []
# 
# set()

二、Dict的元素添加、修改、删除        

示例:

.update()                           # Adds items. Replaces ones with matching keys.
value = .pop(key)                         # Removes item or raises KeyError.

用法:

1、Dict的元素添加与修改

(1)直接添加与直接修改

# 直接添加
my_dict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e'}
my_dict[5] = 'f'
print(my_dict)
# {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}

# 直接修改
my_dict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e'}
my_dict[0] = 'f'
print(my_dict)
# {0: 'f', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}

(2)update的用法示例(使用update添加与修改)

# .update()                           # Adds items. Replaces ones with matching keys.

# update的用法1:更新最新key对应的值
my_dict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e'}
update_dict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'f'}
my_dict.update(update_dict)
print(my_dict)
# {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'f'}


# update的用法2:若有新的键值对,则更新新的键值对
my_dict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e'}
update_dict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f'}
my_dict.update(update_dict)
print(my_dict)
# {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}


# update的用法3:若更新空字典,则无改变
my_dict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e'}
update_dict = {}
my_dict.update(update_dict)
print(my_dict)
# {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}

2、Dict元素的删除 

(1)pop的用法示例

# value = .pop(key)                         # Removes item or raises KeyError.

my_dict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e'}
my_dict.pop(0)
print(my_dict)
# {1: 'b', 2: 'c', 3: 'd', 4: 'e'}

三、Dict的元素查询

示例:

 = .keys()                          # Coll. of keys that reflects changes.
 = .values()                        # Coll. of values that reflects changes.
 = .items()                         # Coll. of key-value tuples that reflects chgs.
value  = .get(key, default=None)          # Returns default if key is missing.
value  = .setdefault(key, default=None)   # Returns and writes default if key is missing.

用法:

1、keys的用法示例(查询所有键)

#  = .keys()                          # Coll. of keys that reflects changes.

# keys的用法
my_dict = {0:'a', 1:'e', 2:'c', 4:'f', 3:'b'}
my_keys = my_dict.keys()
print(my_keys)
# dict_keys([0, 1, 2, 4, 3])

2、values的用法示例(查询所有值)

#  = .values()                        # Coll. of values that reflects changes.

# values的用法
my_dict = {0:'a', 1:'e', 2:'c', 4:'f', 3:'b'}
my_values = my_dict.values()
print(my_values)
# dict_values(['a', 'e', 'c', 'f', 'b'])

3、items的用法示例

#  = .items()                         # Coll. of key-value tuples that reflects chgs.

# items的用法
my_dict = {0:'a', 1:'e', 2:'c', 4:'f', 3:'b'}
my_items = my_dict.items()
print(my_items)
# dict_items([(0, 'a'), (1, 'e'), (2, 'c'), (4, 'f'), (3, 'b')])

4、get的用法示例(根据key来获取值)

# value  = .get(key, default=None)          # Returns default if key is missing.

# get的用法1
my_dict = {0:'a', 1:'e', 2:'c', 4:'f', 3:'b'}
my_value = my_dict.get(1)
print(my_value)
# e

# get的用法2
my_dict = {0:'a', 1:'e', 2:'c', 4:'f', 3:'b'}
my_value = my_dict.get(5)
print(my_value)
# None

my_value = my_dict.get(5, 'error')
print(my_value)
# error

5、setdefault的用法示例

# value  = .setdefault(key, default=None)   # Returns and writes default if key is missing.

# setdefault的用法1:若存在key,则返回对应值
my_dict = {0:'a', 1:'e', 2:'c', 4:'f', 3:'b'}
my_value = my_dict.setdefault(3, 'h')
print(my_value)
print(my_dict)
# b
# {0: 'a', 1: 'e', 2: 'c', 4: 'f', 3: 'b'}


# setdefault的用法2:若不存在key,则添加对应值
my_dict = {0:'a', 1:'e', 2:'c', 4:'f', 3:'b'}
my_value = my_dict.setdefault(5, 'error')
print(my_value)
print(my_dict)

四、Dict的其他用法示例

1、生成相同value值的key集合

# {k for k, v in .items() if v == value}    # Returns set of keys that point to the value.

# 生成相同value的key集合
my_dict = {0:'a', 1:'a', 2:'a', 3:'d', 4:'e'}
new_set = {k for k, v in my_dict.items() if v == 'a'}
print(new_set)
# {0, 1, 2}

 2、筛选对应key的键值对到新的字典中

# {k: v for k, v in .items() if k in keys}  # Returns a dictionary, filtered by keys.

# 筛选对应key的键值对到新的字典中
my_dict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e'}
keys = [0, 1, 2]
new_dict = {k:v for k, v in my_dict.items() if k in keys}
print(new_dict)
# {0: 'a', 1: 'b', 2: 'c'}

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号