文章目录
- 字典
-
- 获取字典的key与value
- 字典的删除与复制操作
- 字典的添加
- 字典成员运算符
- 字典popitem
- 所有数据类型与布尔值的关系
字典
获取字典的key与value
my_dict = {'name':'dewei', 'age':33}
print (my_dict.keys())
>>dict_keys(['name', 'age'])
key_list = list (my_dict.keys())
print (key_list)
>>['name', 'age']
my_dict = {'name':'dewei', 'age':33}
print (my_dict['name'])
>>dewei
my_dict = {'name':'dewei', 'age':33}
print (my_dict.get('name'))
print (my_dict.get('sss'))
print (my_dict.get('sss','ddd'))
>>dewei
>>None
>>ddd
my_dict = {'name':'dewei', 'age':33}
print (my_dict.values())
>>dict_values(['dewei', 33])
字典的删除与复制操作
my_dict = {'name':'dewei', 'age':33}
my_dict.clear()
print (my_dict)
>>{}
my_dict = {'name':'dewei', 'age':33}
pop_value = my_dict.pop ('age')
print (pop_value)
print (my_dict)
>>33
>>{'name': 'dewei'}
my_dict = {'name':'dewei', 'age':33}
del my_dict['name']
print (my_dict)
>>{'age': 33}
del my_dict
my_dict = {'name':'dewei', 'age':33}
new_dict = my_dict.copy()
print (new_dict)
print (id(my_dict) != id(new_dict))
>>{'name': 'dewei', 'age': 33}
>>True
字典的添加
tinydict = {'Name': 'Zara', 'Age': 7}
tinydict2 = {'Sex': 'female' }
tinydict.update(tinydict2)
print ("Value : %s" % tinydict)
>>Value : {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}
tinydict['hobby'] = 'basketball'
print ("Value : %s" % tinydict)
>>Value : {'Name': 'Zara', 'Age': 7, 'Sex': 'female', 'hobby': 'basketball'}
字典成员运算符
my_dict = {'name':'dewei', 'age':33}
print ('name' in my_dict)
print ('name' not in my_dict)
>>True
>>False
字典popitem
my_dict = {'name':'dewei', 'age':33}
print (my_dict.popitem())
>>('age', 33)
所有数据类型与布尔值的关系
数据类型 |
True |
False |
int |
非0 |
0 |
float |
非0.0 |
0.0 |
str |
len(str) != 0 |
len(str) == 0即’‘ |
list |
len(list) != 0 |
len(list)==0即[] |
tuple |
len(tuple)!=0 |
len(tuple)==0即() |
dict |
len(dict)!=0 |
len(dict)==0即{} |
None |
not None |
None |