python dict字典詳解

1.字典特點

字典是另一種可變容器模型,且可存儲任意類型對象。
字典的每個鍵值(key=>value)對用冒號(:)分割,每個對之間用逗號(,)分割,整個字典包括在花括號
例如:d = {key1 : value1, key2 value2 }
鍵必須是唯一的,但值則不必
不允許同一個鍵出現兩次。創建時如果同一個鍵被賦值兩次,後一個值會被記住

2.字典內置函數

  • 1 cmp(dict1, dict2)比較兩個字典元素。
  • 2 len(dict)計算字典元素個數,即鍵的總數。
  • 3 str(dict)輸出字典可打印的字符串表示。
  • 4 type(variable)返回輸入的變量類型,如果變量是字典就返回字典類型。

3.字典內置方法

1 dict.clear()                    刪除字典內所有元素
2 dict.copy()                     返回一個字典的淺複製
3 dict.fromkeys(seq[, val])       創建一個新字典,以序列 seq 中元素做字典的鍵,val 爲字典所有鍵對應的初始值
4 dict.get(key, default=None)     返回指定鍵的值,如果值不在字典中返回default值
5 dict.has_key(key)               如果鍵在字典dict裏返回true,否則返回false
6 dict.items()                    以列表返回可遍歷的(鍵, 值) 元組數組
7 dict.keys()                     以列表返回一個字典所有的鍵
8 dict.setdefault(key, default=None)和get()類似, 但如果鍵不存在於字典中,將會添加鍵並將值設爲default
9 dict.update(dict2)              把字典dict2的鍵/值對更新到dict裏
10 dict.values()                  以列表返回字典中的所有值
11 pop(key[,default])             刪除字典給定鍵 key 所對應的值,返回值爲被刪除的值。key值必須給出。 否則,返回default值。
12 popitem()                      隨機返回並刪除字典中的一對鍵和值。

4.方法運用

$ cat dict1.py
#!/usr/bin/python
#!---coding:utf-8----

dic1={'age': 18, 'name': 'alex', 'hobby': 'girl'}
dic2={'1':'111','2':'222'}
dic2={'1':'111','name':'222'}

dic1.update(dic2)
print(dic1)
print(dic2)
for k in dic2:  #等同update()
    dic1[k] = dic2[k]
print dic1

[root@localhost dict]$ python dict1.py 
{'1': '111', 'hobby': 'girl', 'age': 18, 'name': '222'}
{'1': '111', 'name': '222'}
{'1': '111', 'hobby': 'girl', 'age': 18, 'name': '222'}

  • del
  • pop(‘key’)
  • popitem()
  • clear()
cat dict3.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First', 'weight': 56, 'gender': 'man'};

del dict['Name']; # 刪除鍵是'Name'的條目
print dict

print(dict.pop('Age')) #刪除字典中指定鍵值對,並返回該鍵值對的值

ret = dict.pop('Class')
print(ret)
print(dict)

a = dict.popitem() #隨機刪除某組鍵值對,並以元組方式返回值
print(a, dict)

dict.clear();     # 清空詞典所有條目
del dict ;        # 刪除詞典
print dict

[root@localhost dict]# python dict3.py 
{'gender': 'man', 'Age': 7, 'weight': 56, 'Class': 'First'}
7
First
{'gender': 'man', 'weight': 56}
(('gender', 'man'), {'weight': 56})
<type 'dict'>

$ cat dict2.py
#!/usr/bin/python
#!---coding:utf-8----

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # 修改已存在的鍵值
dict['School'] = "DPS School"; # 增加新的鍵值對
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

[root@localhost dict]$ python dict2.py 
dict['Age']:  8
dict['School']:  DPS School

$ cat dict4.py 
#!/usr/bin/python
#!---coding:utf-8----

dict={'age': 18, 'name': 'alex', 'hobby': 'girl'}
print(dict['name'])
print(list(dict.keys()))
print(list(dict.values()))
print(list(dict.items()))
it = dict.iteritems()
print it
print dict.get("name", "girl") 
print dict.get("e", 18)   
if "name" in dict:  #等同get()
    print dict["name"]
else:
    print "None"

[root@localhost dict]$ python dict4.py 
alex
['hobby', 'age', 'name']
['girl', 18, 'alex']
[('hobby', 'girl'), ('age', 18), ('name', 'alex')]
<dictionary-itemiterator object at 0x7f93657ad418>
alex
18
alex

dict.fromkeys()

$ cat dict5.py 
#!/usr/bin/python

seq = ('name', 'age', 'sex')

dict = dict.fromkeys(seq)
print "New Dictionary : %s" %  str(dict)

dict = dict.fromkeys(seq, 10)
print "New Dictionary : %s" %  str(dict)
[root@localhost dict]$ python  dict5.py 
New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

4設置默認值

$ cat dict6.py 
#!/usr/bin/python
#!---coding:utf-8----

dict = {}
dict.setdefault("a")
print dict
dict["a"] = "apple"
dict.setdefault("a","default")
print dict
[root@localhost dict]$ python  dict6.py 
{'a': None}
{'a': 'apple'}

5.字典排序

$ cat dict7.py 
#!/usr/bin/python
#!---coding:utf-8----

dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}
#按照key排序
print sorted(dict.items(), key=lambda d: d[0])
#按照value排序 
print sorted(dict.items(), key=lambda d: d[1])
[root@localhost dict]$ python dict7.py 
[('a', 'apple'), ('b', 'grape'), ('c', 'orange'), ('d', 'banana')]
[('a', 'apple'), ('d', 'banana'), ('b', 'grape'), ('c', 'orange')]

6.字典拷貝

淺拷貝

$ cat dict8.py 
#!/usr/bin/python
#!---coding:utf-8----

dict = {"a" : "apple", "b" : "grape"}
dict2 = {"c" : "orange", "d" : "banana"}
dict2 = dict.copy()
print dict2
[root@localhost dict]$ python dict8.py 
{'a': 'apple', 'b': 'grape'}

深拷貝

$ cat dict9.py 
#!/usr/bin/python
#!---coding:utf-8----

import copy
dict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}
dict2 = copy.deepcopy(dict)
dict3 = copy.copy(dict)   
print(copy1 == copy2)   # True
print(copy1 is copy2)   # False
dict2["b"]["g"] = "orange"  #dict2深拷貝相當於獨立object
print dict
dict3["b"]["g"] = "orange"
print dict
[root@localhost dict]$ python dict9.py
True
False
{'a': 'apple', 'b': {'o': 'orange', 'g': 'grape'}}
{'a': 'apple', 'b': {'o': 'orange', 'g': 'orange'}}

7.字典遍歷

遍歷key

cat dict10.oy
#!/usr/bin/python
#!---coding:utf-8----
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}

for k in dict:
 print k
for k in dict:
 print k,
for key in dict.iterkeys():
    print key
for key in dict.keys():
    print key,
[root@localhost dict]# python dict10.oy 
a
c
b
d
a c b d a
c
b
d
a c b d



遍歷值

$ cat dict11.py
#!/usr/bin/python
#!---coding:utf-8----
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}

for k in dict:    #遍歷value
  print dict[k]
for k in dict:    #遍歷value不換行
  print dict[k],
for value in dict.itervalues():
    print value,
for value in dict.values():
    # d.values() -> [2, 1, 3]
    print value
[root@localhost dict]$  python dict11.py 
apple
grape
banana
orange
apple grape banana orange apple grape banana orange apple
grape
banana
orange

遍歷keys和values

$ cat dict12.py
#!/usr/bin/python
#!---coding:utf-8----
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}

for key, value in dict.iteritems():
    # d.iteritems: an iterator over the (key, value) items
    print key,'corresponds to',dict[key]
for key, value in dict.items():
    # d.items(): list of d's (key, value) pairs, as 2-tuples
    # [('y', 2), ('x', 1), ('z', 3)]
    print key,'corresponds to',value
[root@localhost dict]$  python dict12.py 
a corresponds to apple
c corresponds to grape
b corresponds to banana
d corresponds to orange
a corresponds to apple
c corresponds to grape
b corresponds to banana
d corresponds to orange

8.函數字典傳參

$ cat dict13.py
#!/usr/bin/python
#!---coding:utf-8----

dic={"m": 1,"n": 2,"q": 3}
def dics(qwe):
    print qwe
 
dics(dic)

[root@localhost dict]$ python dict13.py 
{'q': 3, 'm': 1, 'n': 2}

9.字典推導式

語法一:

key:字典中的key
value:字典中的value
dict.items():序列
condition:條件表達式
key_exp:在for循環中,如果條件表達式condition成立(即條件表達式成立),返回對應的key,value並作key_exp,value_exp處理
value_exp:在for循環中,如果條件表達式condition成立(即條件表達式成立),返回對應的key,value並作key_exp,value_exp處理
{key_exp:value_exp for key,value in dict.items() if condition}

語法二:

key:字典中的key
value:字典中的value
dict.items():序列
condition:條件表達式
key_exp:在for循環中,如果條件表達式condition成立(即條件表達式成立),返回對應的key,value並作key_exp,value_exp處理
value_exp1:在for循環中,如果條件表達式condition成立(即條件表達式成立),返回對應的key,value並作key_exp,value_exp1處理
value_exp2:在for循環中,如果條件表達式condition不成立(即條件表達式不成立),返回對應的key,value並作key_exp,value_exp2處理
{key_exp:value_exp1 if condition else value_exp2 for key,value in dict.items()}
$ cat dict14.py
#!/usr/bin/python
#!---coding:utf-8----

dict1 = {"a":10,"B":20,"C":True,"D":"hello world","e":"python教程"}
dict2 = {key:value for key,value in dict1.items() if key.islower()}
print(dict2)
dict3 = {key.lower():value  for key,value in dict1.items() }
print(dict3)
dict4 = {key:value if key.isupper() else "error" for key,value in dict1.items() }
print(dict4)
[root@localhost dict]$  python3.8 dict14.py 
{'a': 10, 'e': 'python教程'}
{'a': 10, 'b': 20, 'c': True, 'd': 'hello world', 'e': 'python教程'}
{'a': 'error', 'B': 20, 'C': True, 'D': 'hello world', 'e': 'error'}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章