字典

表示形式

dic_1={'a':22,'b':'f'}
print(dic_1)
print('*'*50)
dic_2=dict(a=1,b=2,c=5)
print(dic_2)
{'a': 22, 'b': 'f'}
**************************************************
{'a': 1, 'b': 2, 'c': 5}

存取

dic={'a':1,"b":2}
print(f"first dic['a']:{dic['a']}")
dic['a']=4
print(f"second dic['a']:{dic['a']}")
first dic['a']:1
second dic['a']:4

len长度

print(len(dic))
2

not in or in

print(2 in dic)
print('a' in dic)
False
True

del删除

del dic['b']
print(dic)
print(dic.get('a'))
print(dic.get('b'))
print(dic)
{'a': 4}
4
None
{'a': 4}

pop删除

dic.pop('a')
print(dic)
{}

循环

dic={'a':1,"b":2}
for k,v in dic.items():
    print(k,v)
a 1
b 2

get取值

print(dic.get('a'))
1
print(dic.get('a'))
dic1 = {'a': 1, 'b': 2}
dic2 = {'c': 3}
dic1.update(dic2)
print(f"dic1: {dic1}")
1
dic1: {'a': 1, 'b': 2, 'c': 3}

fromkeys

dic = dict.fromkeys(['name', 'age', 'sex'], None)
print(f"dic: {dic}")

dic: {'name': None, 'age': None, 'sex': None}

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[11], line 1
----> 1 dic = dict.fromkeys(['name', 'age', 'sex'], 1,2,3)
      2 print(f"dic: {dic}")


TypeError: fromkeys expected at most 2 arguments, got 4

posted @ 2024-01-31 17:12  泥跟沃丸吗  阅读(3)  评论(0编辑  收藏  举报