Python编程学习9:Python字典使用详解(创建字典,访问字典,修改字典,字典排序)

字典反映的是一种映射关系,由键值对组成,键的取值唯一,不可重复。需注意键的取值必修是不可变的,如字符串,int型整数,使用列表等可变变量会出错。

1. 创建字典:

   (1)直接使用dict1 = {key1:value1, key2=value2} 形式

    (2)使用dict1 = dict(key1=value1, key2=value2) 形式,注意使用此形式时,key不可直接使用数字,否则会报错

dict1 = {1:'one',3:'three',2:'two',8:'eight',9:'nine'}
print(dict1)
{1: 'one', 3: 'three', 2: 'two', 8: 'eight', 9: 'nine'}

dict3 = dict(一='one',三='three',二='two',八='eight',九='nine')
print(dict3)
{'一': 'one', '三': 'three', '二': 'two', '八': 'eight', '九': 'nine'}

dict2 = dict(1='one',3='three',2='two',8='eight',9='nine')
print(dict2)
  File "<ipython-input-15-f5500fbe1192>", line 3
    dict2 = dict(1='one',3='three',2='two',8='eight',9='nine')
                ^
SyntaxError: keyword can't be an expression

(3)直接使用dict1[key1] = value1

dict4 = {}
dict4[1] = 'one'; dict4[3] = 'three'
print(dict4)
{1: 'one', 3: 'three'}

(4)使用dict.fromkeys()函数:注意fromkeys()会返回一个新字典,而不是对原字典本身进行修改。

dict5 = {}
dict5.fromkeys((1,2,3),('one','two','three'))

{1: ('one', 'two', 'three'),
 2: ('one', 'two', 'three'),
 3: ('one', 'two', 'three')}

dict5.fromkeys((1,2,3),'数字')
{1: '数字', 2: '数字', 3: '数字'}


2. 访问字典

  (1)直接使用dict[key]

dict3 = dict(一='one',三='three',二='two',八='eight',九='nine')
print(dict3['八'])
eight

(2)get方法:此方法只访问不修改字典,第一个参数传入键,第二个可传入一个字符串,如果键不在字典中,则返回此字符串

dict3.get('八')
'eight'

dict3.get('十',"十不在字典中")
'十不在字典中'

dict3
{'一': 'one', '三': 'three', '九': 'nine', '二': 'two', '八': 'eight'}

(3)dict.keys(), dict.values(), dict.items()可分别返回字典键、值、键值对组成的元组

print(a.keys())
print(a.values())
print(a.items())

dict_keys(['一', '三', '九', '二', '八', '六', '七'])
dict_values(['one', 3, 9, 'two', 'eight', 6, 7])
dict_items([('一', 'one'), ('三', 3), ('九', 9), ('二', 'two'), ('八', 'eight'), ('六', 6), ('七', 7)])


3. 修改字典:

    (1)del 方法: 可删除某个键值对,也可删除整个字典
del dict3['八']
dict3
{'一': 'one', '三': 'three', '九': 'nine', '二': 'two'}

del dict3
dict3
NameError                                 Traceback (most recent call last)
<ipython-input-31-10f6b9bbed43> in <module>()
      1 del dict3
----> 2 dict3

NameError: name 'dict3' is not defined

(2)dict.clear() 方法清除字典内容,但不删除字典本身

a = {'一': 'one', '三': 'three', '九': 'nine', '二': 'two', '八': 'eight'}
b = a
a.clear()
print(a)
print(b)

{}
{}

      注意:慎用dict = {}来清除字典内容,容易造成数据泄露。如下例子,执行a={}后,仍可通过b获取字典内容。

a = {'一': 'one', '三': 'three', '九': 'nine', '二': 'two', '八': 'eight'}
b = a
a = {}
print(a)
print(b)

{}
{'一': 'one', '三': 'three', '九': 'nine', '二': 'two', '八': 'eight'}

(3)dict.pop(key)和popitem()

       dict.pop(key)指定删除并返回key的键值对;dict.popitem()则随机删除并返回一个键值对(因为字典是无序的)

a = {'一': 'one', '三': 'three', '九': 'nine', '二': 'two', '八': 'eight'}
a.pop('三')
print(a)

{'一': 'one', '九': 'nine', '二': 'two', '八': 'eight'}
a.popitem()
print(a)

{'一': 'one', '九': 'nine', '二': 'two'}

(4)setdefault()方法: dict.setdefault(key1, value1) ,如果键在原字典中存在,则不对其做修改,如果键在原字典中不存在,则在原字典中添加key1=value1的键值对。

a = {'一': 'one', '三': 'three', '九': 'nine', '二': 'two', '八': 'eight'}
a.setdefault('五','five')
{'一': 'one', '三': 'three', '九': 'nine', '二': 'two', '八': 'eight', '五': 'five'}

a.setdefault('三',3)
print(a)
{'一': 'one', '三': 'three', '九': 'nine', '二': 'two', '五': 'five', '八': 'eight'}

(5)update方法: 传入一个字典作为参数,该字典中的键如果出现在原字典中,则直接对原字典中的键值对进行修改,如果不在原字典中,则直接添加到原字典。

a = {'一': 'one', '三': 'three', '九': 'nine', '二': 'two', '八': 'eight'}
a.update({'六':6,'七':7,'三':3, '九':9})
print(a)

{'一': 'one', '三': 3, '九': 9, '二': 'two', '八': 'eight', '六': 6, '七': 7}


4. 字典的排序问题:先获取字典的items(),再使用sorted()函数

sorted(iterable,key,reverse),sorted一共有iterable,key,reverse这三个参数。

    其中iterable表示可以迭代的对象,例如可以是dict.items()、dict.keys()等,key是一个函数,用来选取参与比较的元素,reverse则是用来指定排序是倒序还是顺序,reverse=true则是倒序,reverse=false时则是顺序,默认时reverse=false。

    (1)直接使用sorted(dict) ,则只对dict的key进行排序,并返回排序结果

a = {'一': 1, '三': 3, '九':9, '二': 2, '八': 8}
sorted(a)
[1, 2, 3, 8, 9]

    (2)要按key值或value值对字典排序,则可以使用如下语句:

a = {1: 'one', 3: 'three', 9: 'nine', 2: 'two', 8: 'eight'}
sorted(a.items(),key = lambda item:item[0],reverse=True)

[(9, 'nine'), (8, 'eight'), (3, 'three'), (2, 'two'), (1, 'one')]

a = {'一': 1, '三': 3, '九':9, '二': 2, '八': 8}
sorted(a.items(),key = lambda item:item[1],reverse=True)

[('九', 9), ('八', 8), ('三', 3), ('二', 2), ('一', 1)]



猜你喜欢

转载自blog.csdn.net/zhuzuwei/article/details/80576066