python字典基础

Dictionarys

1. 定义、初始化、常用方法

  • 字典的键类似于列表的索引,但是它必须为不可变的数据类型(字符串、整数等)
  • 字典的值与列表的值一样可以为任意python对象
  • 使用defaultdict可以指定字典值的类型
my_dict = {}

# 指定值的类型
from collections import defaultdict
my_dict = defaultdict(int)

1.1 初始化

dict1 = {'value1': 1.6, 'value2': 10, 'name': 'John Doe'}
dict2 = dict(value1=1.6, value2=10, name='John Doe')

print(dict1)  # {'value1': 1.6, 'value2': 10, 'name': 'John Doe'}
print(dict2)  # {'value1': 1.6, 'value2': 10, 'name': 'John Doe'}

print('equal: {}'.format(dict1 == dict2))  # True

1.2 常用方法

  • 查看键:dict.keys()
  • 查看值:dict.values()
  • 查看键值对:dict.items()
print('keys: {}'.format(dict1.keys()))  # keys: dict_keys(['value1', 'value2', 'name'])
print('values: {}'.format(dict1.values()))  # values: dict_values([1.6, 10, 'John Doe'])
print('items: {}'.format(dict1.items()))  # items: dict_items([('value1', 1.6), ('value2', 10), ('name', 'John Doe')])

2. 增加字典中的元素

my_dict = {}
my_dict['key1'] = 'value1'
my_dict['key2'] = 99
my_dict['key1'] = 'new value'  # 为存在的键重新赋值
print(my_dict)  # {'key1': 'new value', 'key2': 99}

2. 删除字典中的元素

  • del关键字
my_dict = {'key1': 'value1', 'key2': 99, 'keyX': 'valueX'}
del my_dict['keyX']
print(my_dict)  # {'key1': 'value1', 'key2': 99}
  • Dict.pop()
my_dict = {'key1': 'value1', 'key2': 99, 'keyX': 'valueX'}
my_dict.pop('keyX')
print(my_dict)  # {'key1': 'value1', 'key2': 99}
  • Dict.popitem() 删除字典最后一个元素
my_dict = {'key1': 'value1', 'key2': 99, 'keyX': 'valueX'}
my_dict.popitem()
print(my_dict)  # {'key1': 'value1', 'key2': 99}

3. 查询字典中键对应的值

  • 直接查
    若查询的键不在字典空则报错
my_dict = {'a', 1, 'b': 2}
print(my_dict['a'])  # 1
  • Dict.get()
    若查询的键不在字典空则返回空值,可以设置返回自定义的值
my_dict = {'a', 1, 'b': 2}
print(my_dict.get('a'))  # 1
print(my_dict.get('c', 0))  # 0

4. 为字典的键设置默认值

  • Dict.setdefault()
my_dict = {'a': 1, 'b': 2, 'c': 3}
a = my_dict.setdefault('a', 'my default value')  # a: 1
d = my_dict.setdefault('d', 'my default value')  # d: my default value
print('a: {}\nd: {}\nmy_dict: {}'.format(a, d, my_dict))  # my_dict: {'a': 1, 'b': 2, 'c': 3, 'd': 'my default value'}

5. 合并两个字典

  • Dict.setdefault()
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3}
dict1.update(dict2)
print(dict1)

# 如果两个字典中有相同的键:
dict1.update({'c': 4})  # {'a': 1, 'b': 2, 'c': 3}
print(dict1)  # {'a': 1, 'b': 2, 'c': 4}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值