Python字典(dict)简介

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chuan_day/article/details/75331676

Python字典(dict)简介

Python字典就是键值对的形式存储的一种映射类型,key:value,key在整个字典中是唯一的,value是随意的。key重复时会被覆盖。字典是无序的,即每次输出的键值对的顺序是随机的。

1、创建dict
创建空的字典
dict1 = {}
创建非空字典
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
以上摘自文档。

2、得到字典长度
dict2 = {'one': 1, 'two': 2, 'three': 3}
print(len(dict2))
输出:3
3、查询字典信息
dict2 = {'one': 1, 'two': 2, 'three': 3}
print(dict2['one'])#输出:1
print(dict2.get('one',4))#输出:1
print(dict2.get('four',4))#输出:4
print(dict2)#dict2不变
get方法的特别之处在与如果key存在字典中,那么就输出value,如果不存在那么就输出指定的值,未指定默认值就是None。
4、清空字典
dict2.clear()
print(dict2)#输出:{}
5、增加字典键值对
dict2['four']=4
print(dict2)#输出:{'four': 4, 'one': 1, 'three': 3, 'two': 2

dict2.setdefault('five',5)
print(dict2)#输出:{'four': 4, 'one': 1, 'three': 3, 'five': 5, 'two': 2}
6、删除字典键值对(或叫元素)
dict2.pop('one')#pop出一个存在的key的键值对,如果不存在key,raise KeyError错误
print(dict2)#输出:{'five': 5, 'two': 2, 'three': 3, 'four': 4}
del dict2['two']#删除key=two的键值对,如果不存在key,raise KeyError错误
print(dict2)#输出:{'five': 5, 'three': 3, 'four': 4}
dict2.popitem()#随意pop掉一组键值对
print(dict2)#输出:{'three': 3, 'four': 4}
7、查询字典中的keys,values,items即为键集合,值集合,键值对集合,而这种集合被称为Dictionary view objects(字典视图对象),类似于迭代器,
      不是一次全部生成,放入内存中

print(dict2.keys())
#输出:dict_keys(['three', 'two', 'five', 'four', 'one'])
print(list(dict2.keys()))
#直接转化为list,输出:['three', 'two', 'five', 'four', 'one']
for k in dict2.keys():
    print(k)
three
two
five
four
one
print(dict2.values(),list(dict2.values()))
#输出:dict_values([3, 2, 5, 4, 1]) [3, 2, 5, 4, 1]
for v in dict2.values():
    print(v)
#输出:
3
2
5
4
1
print(dict2.items())
for i in dict2.items():
    print(i)
('three', 3)
('two', 2)
('five', 5)
('four', 4)
('one', 1)
很明显输出的结果都是无序的。
8、更新dict
dict2.update({'one':11})
#如果更新的时候key存在,那么就覆盖value
print(dict2)#输出:{'three': 3, 'five': 5, 'one': 11, 'two': 2, 'four': 4}
dict2.update({'ten':10})
#如果更新的key不存在dict中时,就添加
print(dict2)#输出:{'three': 3, 'ten': 10, 'five': 5, 'one': 11, 'two': 2, 'four': 4}

9、判断key是否存在
print('one' in dict2)#输出:True
print('sax' not in dict2)#输出:True

以上为常用方法,关键还是在代码中能熟练灵活的运用







猜你喜欢

转载自blog.csdn.net/chuan_day/article/details/75331676
今日推荐