【python基础】字典的使用

1. 字典的基本性质:

  • 使用{ }花括号表示;
  • 关键字: dict;
  • 保存的元素:键-值对(key-value);
  • 空字典的两种表示方法:
dict1 = {}
dict1 = dict()
  • 有内容的字典定义:
dict3 = {'ID':'110110229','name':'lily'}
dict4 = dict([('name','lucky'),('age','18')])

2. 字典的添加

空字典的定义,字典的添加,添加时若有同名的key,会出现value的值覆盖;key是唯一的,value值是可以重复的。

dict1 = {}
dict1['brand'] = 'huawei'
print(dict1)
{'brand': 'huawei'}

3. 字典的取值操作

字典的查找使用key进行value的获取。

dict1 = {}
dict1['brand'] = 'huawei'
dict1['name'] = 'tom'
print(dict1)
print(dict1['name'])
{'brand': 'huawei', 'name': 'tom'}
tom

4. 字典中items()的使用方法

item()方法把字典中每对key和value组成一个元组,并把这些元组放在列表中返回。

dict1 = {'name':'tom','age':18}
for i in dict1:
    print(i)

print(dict1.items())
for key,value in dict1.items():# 遍历拿出来的是元组
    print(key,value)
    if value == 18:
        print(key)
age
dict_items([('name', 'tom'), ('age', 18)])
name tom
age 18
age

4. 字典中的值获取

  1. 1 使用keys()和 values()获取字典的值
dict1 = {'name':'tom','age':18}

result1 = dict1.keys()
result = dict1.values()

print(result1)
print(result)

输出结果

print(result1)
print(result)

4.2 dict.get(key, default=None) key表示字典中要查找的键,default表示如果指定键的值不存在时,返回该默认值。

dict1 = {'name':'tom','age':18}
#dict.get(key, default=None)  key表示字典中要查找的键,default表示如果指定键的值不存在时,返回该默认值。
result = dict1.get('gender','girl')
print(result)

输出结果:

girl

5. 字典的删除

根据key值来进行索引

dict1 = {'name':'tom','age':18}
print(dict1)
del dict1['name']
print(dict1)

输出:

{'name': 'tom', 'age': 18}
{'age': 18}

pop()

dict1 = {'name':'tom','age':18}
print(dict1)

result = dict1.pop('name')
print(result)
print(dict1)

返回:

{'name': 'tom', 'age': 18}
tom
{'age': 18}

popitem():

dict1 = {'name':'tom','age':18,'33':'ww','ert':'ttr'}
print(dict1)
# result = dict1.pop('name')
# print(result)
# print(dict1)
result = dict1.popitem()
print(result)
print(dict1)

result1 = dict1.popitem()
print(result1)
print(dict1)

输出:

{'name': 'tom', 'age': 18, '33': 'ww', 'ert': 'ttr'}
('ert', 'ttr')
{'name': 'tom', 'age': 18, '33': 'ww'}
('33', 'ww')
{'name': 'tom', 'age': 18}

字典的合并updata()

把字典1加到字典2上。


dict1 = {'name':'tom','age':18,'33':'ww','ert':'ttr'}
dict2 = {'2r':'54','fed':'feww'}

print(dict1)
dict2.update(dict1)

print(dict1)
print(dict2)

输出:

{'name': 'tom', 'age': 18, '33': 'ww', 'ert': 'ttr'}
{'name': 'tom', 'age': 18, '33': 'ww', 'ert': 'ttr'}
{'2r': '54', 'fed': 'feww', 'name': 'tom', 'age': 18, '33': 'ww', 'ert': 'ttr'}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值