字典dict

starry_lucky發表於2020-12-06

1.定義:

a = {‘q’:1, ‘w’:2 ,‘e’:3}
b = {

2.取值

a = {'q':1, 'w':2 ,'e':3}
k = a.keys()
v = a.values()
t = a.items()
print(k,'\t',v,'\t',t)
print(list(k),'\t',list(v),'\t',list(t))

結果:
dict_keys([‘q’, ‘w’, ‘e’]) dict_values([1, 2, 3]) dict_items([(‘q’, 1), (‘w’, 2), (‘e’, 3)])
[‘q’, ‘w’, ‘e’] [1, 2, 3] [(‘q’, 1), (‘w’, 2), (‘e’, 3)]

3.計算

  • 取value的和
a = {'q':1, 'w':2 ,'e':3}
print(sum(a.values()))

結果:
6

  • 取最大值
a = {'q':1, 'w':2 ,'e':3}
print(max(a.values()))

結果:
3

a = {'q':1, 'w':2 ,'e':3}
print(min(a.values()))

結果:
1

賦值/修改

  • 修改value
b = {'z':[1,0],'x':{'n':5,'m':6},'c':'?'}
b['z'] = 'o'
print(b)

結果:
{‘z’: ‘o’, ‘x’: {‘n’: 5, ‘m’: 6}, ‘c’: ‘?’}

b = {'z':[1,0],'x':{'n':5,'m':6},'c':'?'}
b['z'][1] = 1
print(b)

結果:
{‘z’: [1, 1], ‘x’: {‘n’: 5, ‘m’: 6}, ‘c’: ‘?’}

b = {'z':[1,0],'x':{'n':5,'m':6},'c':'?'}
b['x']['n'] = 'p'
print(b)

結果:
{‘z’: [1, 0], ‘x’: {‘n’: ‘p’, ‘m’: 6}, ‘c’: ‘?’}

b = {'z':[1,0],'x':{'n':5,'m':6},'c':'?'}
b['x'] = 'p'
print(b)

結果:
{‘z’: [1, 0], ‘x’: ‘p’, ‘c’: ‘?’}

  • 修改key(只能間接)
a = {'q':1, 'w':2 ,'e':3}
a['h'] = a.pop('q')
print(a)

結果
{‘w’: 2, ‘e’: 3, ‘h’: 1}

  • 增加鍵值對
a = {'q':1, 'w':2 ,'e':3}
a['r'] = 'g'
print(a)

結果:
{‘q’: 1, ‘w’: 2, ‘e’: 3, ‘r’: ‘g’}

4.刪除/清空

  • del
    • 刪除整個字典
#刪除整個字典
a = {'q':1, 'w':2 ,'e':3}
del a
print(a)

結果
name ‘a’ is not defined

  • 刪除字典某一鍵值對
a = {'q':1, 'w':2 ,'e':3}
del a['q']
print(a)

{‘w’: 2, ‘e’: 3}

  • pop
a = {'q':1, 'w':2 ,'e':3}
a.pop('q')
print(a)

{‘w’: 2, ‘e’: 3}

  • popitem
a = {'q':1, 'w':2 ,'e':3}
a.popitem()
print(a)

{‘q’: 1, ‘w’: 2}

  • clear-清空
a = {'q':1, 'w':2 ,'e':3}
a.clear()
print(a)

{}

5.拼接(update)

無重複鍵則新增,又重複鍵則賦值

  • 無重複鍵
a = {'q':1, 'w':2 ,'e':3}
b = {'z':[1,0],'x':{'n':5,'m':6},'c':'?'}
a.update(b)
print(a)

{‘q’: 1, ‘w’: 2, ‘e’: 3, ‘z’: [1, 0], ‘x’: {‘n’: 5, ‘m’: 6}, ‘c’: ‘?’}

  • 有重複鍵
a = {'q':1, 'w':2 ,'e':3}
b = {'z':[1,0],'w':{'n':5,'m':6},'e':'?'}
a.update(b)
print(a)

{‘q’: 1, ‘w’: {‘n’: 5, ‘m’: 6}, ‘e’: ‘?’, ‘z’: [1, 0]}

6.自動生成字典

  • fromkeys
dict_a = {}
a = ['q','w','e']
dict_a = dict_a.fromkeys(a)
print(dict_a)

{‘q’: None, ‘w’: None, ‘e’: None}

  • zip()
a = ['q','w','e']
b = [1,2,3]
c = dict(zip(a,b))
print(c)

{‘q’: 1, ‘w’: 2, ‘e’: 3}

7.查詢值

  • get():不會新增鍵值對
a = {'q':1, 'w':2 ,'e':3}
print(a.get('q','無該key'))
print(a.get('l','無該key'))
print(a)

1
無該key
{‘q’: 1, ‘w’: 2, ‘e’: 3}

  • setdefault():無則新增
a = {'q':1, 'w':2 ,'e':3}
print(a.setdefault('q','無該key'))
print(a.setdefault('l','無該key'))
print(a)

1
無該key
{‘q’: 1, ‘w’: 2, ‘e’: 3, ‘l’: ‘無該key’}

相關文章