Common operations and methods of dictionary types

Method or operation Description
d[key] = value Set d[key] to value.
key in d If the key exists in d, it returns True, otherwise it returns False.
key not in d Equivalent to not key in d.
clear() Remove all elements in the dictionary.
copy() Return a shallow copy of the original dictionary.
get(key[, default]) If the key exists in the dictionary, return the value of key, otherwise return default. If default is not given, it defaults to None, so this method will never raise a KeyError.
pop(key[, default]) If the key exists in the dictionary, remove it and return its value, otherwise return default. If default is not given and the key does not exist in the dictionary, a KeyError will be raised.
setdefault(key[, default]) New in version 3.8. If the key exists in the dictionary, return its value. If it does not exist, insert the key with the value default and return default. default The default is None.

Example:

d_dict = {
    
    'name': 'xiaoming', 'age': 16}
d_dict['gender'] = 'male'
print(d_dict)
print('name' in d_dict)
print('name' not in d_dict)
d_dict.clear()
print(d_dict)
d_dict = {
    
    'name': 'xiaoming', 'age': 16, 'gender': 'male'}
print(d_dict.copy())
print(d_dict.get('name'))
print(d_dict.get('jhhh'))
print(d_dict.pop('name'))
print(d_dict)
print(d_dict.setdefault('name', 'xiaoming'))
print(d_dict)
print('-' * 120)
# 常用技巧
for k, v in d_dict.items():
    print(k, v)

result:

{
    
    'name': 'xiaoming', 'age': 16, 'gender': 'male'}
True
False
{
    
    }
{
    
    'name': 'xiaoming', 'age': 16, 'gender': 'male'}
xiaoming
None
xiaoming
{
    
    'age': 16, 'gender': 'male'}
xiaoming
{
    
    'age': 16, 'gender': 'male', 'name': 'xiaoming'}
------------------------------------------------------------------------------------------------------------------------
age 16
gender male
name xiaoming

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/plan_jok/article/details/111026989