Python- dictionary to learn the basics of (dict)

Dictionary has a flexible size is set to the key, and the key values ​​of an object, separated by commas for each key, all keys using braces:

adict = {} #定义一个空字典

bdict = {'a': 'hello world', 'b': [1, 2, 3]}

print(bdict)
#打印
    {'a': 'hello world', 'b': [1, 2, 3]}

#插入一个新的键值对
bdict['c'] = 'happy day'
print(bdict)
#打印
    {'a': 'hello world', 'b': [1, 2, 3], 'c': 'happy day'}

#通过键访问数据
print(bdict['a'])
#打印
    'hello world'

#判断一个键是否存在于字典中
bln = 'b' in bdict
print(bln)
#打印
    True

#使用del或者pop方法删除值,pop方法会在删除的同时返回被删的值,并删除键
del bdict['c']
print(bdict)
#打印
    {'a': 'hello world', 'b': [1, 2, 3]}

ret = bdict.pop(b)
print(ret, bdict)
#打印
    [1, 2, 3] {'a': 'hello world'}


#字典的keys和values方法返回字典的键和值的迭代器,另外要注意,键值没有特定的顺序
print(list(blist.keys())
#打印
    ['a']

print(list(blist.values())
#打印
    ['hello world']


#字典的update方法可以将两个字典合并:
adict = {'b': 'bar', 'c': 22}
bdict.update(adict)
print(bdict)
#打印
    {'a': 'hello world', 'b': 'bar', 'c': 22}

#update改变了字典中元素位置,如果在原字典中存在的键,如果传递给update方法的数据也有相同的键,那么就会替换掉原来的值

Get a dictionary and pop methods, there comes with a default value, so you can get:

value = adict.get(key, default_value)

Generates a default value of the dictionary, there is a convenient way:

from collections import defaultdict #导入默认字典模块

adict = defaultdict(list)
for word in words:
    adict[word[0]].append(word)

Dictionary key (key) must be a fixed can not be changed, it can not be an array, can be scalar (integer, float, string) or a tuple (a tuple of objects can not be varied). Want to know what can be used as dictionary keys, we can determine whether it can be hashed, you can check by hash function:

print(hash('string'))
#打印
    5023931463650008331

print(hash((1, 2, (3 ,4)))
#打印
    1097636502276347782

print(hash((1, 2, [3, 4])) #会报错,里面包含了可变的数组,因此是不能哈希化的
#打印
    TypeError

 

Guess you like

Origin blog.csdn.net/pz789as/article/details/93758915