Youth Python Competition Knowledge Point Learning 5--Dictionary

        The dictionary in python is somewhat similar to the Xinhua dictionary we use. Indexes and objects. Xinhua Dictionary stores the relevant content of each word. The dictionary in Python is a container-type data structure that is indexed by key.

1.What is a dictionary

  1. Dictionary is one of the important built-in data in Python. Like a list, it is a mutable sequence.
  2. Data is stored in the form of key-value pairs (key:value). The dictionary is an unordered sequence, and the list is an ordered sequence.
  3. Use {} to define a dictionary.
  4. Dictionary is the only mapping type in the Python language. The dictionary object is mutable. It is a container type that can store any number ofPython objects, which can also include other container types.

2.Creation of dictionary

        The key in the dictionary is very critical data, and the key needs to be used to access the value in the program, so the key in the dictionary cannot be repeated. Two ways to create:

1. Create using {}

When creating, {} should contain multiple key_value pairs. Key and value should be separated by English colons, and multiple key-value pairs should be separated by English commas. Tips for primary school students: The dictionary reads "funny big cat" ({,:}).

# -*- coding: utf-8 -*-
# @Time : 2023年11月05日 10时26分
# @Email : [email protected]
# @Author : Chenfengyi
# @File : 字典.py
# @notice :


treeword = {}  # 空字典
print(treeword)
twoword = {'桌子': 'desk', '书': 'book'}  # key与value均为字符串
print(twoword)
dict3 = {(1, 5): '合格', (1, 3): '优秀', 10: '李明'}  # key为元组,整数,value均为字符串,
print(dict3)
dict3 = {2: '合格', (1, 3): 500, 10: '李明'}
print(dict3)

2. Create using dict() function

When using the dict() function to create a dictionary, you can pass in multiple tuples or list parameters as key_value pairs. Each list or tuple will be a key_value pair, so it can only contain two elements, as follows:

word=((1, 3), (1, 3))
d1=dict(word)
print(d1)
word=((1, 3), (5, 3))
d1=dict(word)
print(d1)
word=[(1, 'good'), (1, 'book')]
d1=dict(word)
print(d1)
word=[('好', 'good'), ('书', 'book')]
d1=dict(word)
print(d1)
dictempty=dict()
print(dictempty)

结果:
{1: 3}
{1: 3, 5: 3}
{1: 'book'}
{'好': 'good', '书': 'book'}
{}

3. Basic usage of dictionary

Note that the dictionary contains multiple k-v pairs, and key is the key data of the dictionary, so operations on the dictionary are based on key

Access value by key

Add value by key

cj={'语文':85,'数学':105,'英语':98}
print(cj)
print(cj['英语'])
print(cj['美术'])

Traceback (most recent call last):
  File "F:/le_python/csdn/字典增删改查.py", line 11, in <module>
    print(cj['美术'])
KeyError: '美术'
{'语文': 85, '数学': 105, '英语': 98}
98

Modify value by key

Delete value by key

cj={'语文':85,'数学':105,'英语':98}
print(cj)
print(cj['英语'])
if '美术' not in cj:
    cj['美术'] = 99
    print('没用美术成绩')
else:
    print(cj['美术'])
print(cj)

del cj['美术']
print(cj)

结果:
{'语文': 85, '数学': 105, '英语': 98}
98
没用美术成绩
{'语文': 85, '数学': 105, '英语': 98, '美术': 99}
{'语文': 85, '数学': 105, '英语': 98}

进程已结束,退出代码 0

Determine whether the key-value pair exists by key

cj={'语文':85,'数学':105,'英语':98}
print(cj)
print(cj['英语'])
if '美术' not in cj:
    print('没用美术成绩')
else:
    print(cj['美术'])


结果:
{'语文': 85, '数学': 105, '英语': 98}
98
没用美术成绩
    A dictionary is equivalent to an index of any immutable type list, and a list is equivalent to a dictionary whose keys can only be integers. Therefore, if the keys of the dictionary to be used in the program are all integer types, you can consider whether they can be replaced by lists.

     Lists do not allow assignment to non-existent indexes, but dictionaries do.

4. Commonly used methods of dictionary

print(dir({}))
print(dir(dict))
lb=dir({})
b=[]
for a in lb:
    if '_' not in a:
        b.append(a)        
print(b)
结果:
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

Commonly used methods:

'clear': Clear the dictionary

 'copy':Copy

 'fromkeys': Create a dictionary using multiple given keys. The default value corresponding to the key is none or the default value can be specified.

cj=dict.fromkeys(['数学','语文'])
print(cj)
cj=dict.fromkeys(('数学','语文'))
print(cj)
cj=dict.fromkeys(('数学','语文'),80)
print(cj)

{'数学': None, '语文': None}
{'数学': None, '语文': None}
{'数学': 80, '语文': 80}

 'items'

 'keys',

'values'

cj=dict.fromkeys(['数学','语文'])
print(cj)
cj=dict.fromkeys(('数学','语文'))
print(cj)
cj=dict.fromkeys(('数学','语文'),80)
print(cj)

print('items',cj.items)
print('keys',cj.keys)
print('values',cj.values)


print('items',list(cj.items()))
print('keys',list(cj.keys()))
print('values',list(cj.values()))

结果:
{'数学': None, '语文': None}
{'数学': None, '语文': None}
{'数学': 80, '语文': 80}
items <built-in method items of dict object at 0x02169180>
keys <built-in method keys of dict object at 0x02169180>
values <built-in method values of dict object at 0x02169180>
items [('数学', 80), ('语文', 80)]
keys ['数学', '语文']
values [80, 80]

 'get': Obtain the value based on the key, which is equivalent to an enhanced version of the [] syntax. Using [] to obtain a non-existent key will cause a keyerro error. get() will return none and will not cause an error.

'pop',

'I drink',

'setdefault',

'update'

Try it yourself when you have time.

Guess you like

Origin blog.csdn.net/fqfq123456/article/details/134227174