当前位置:网站首页>Py06 dictionary mapping dictionary nested key does not exist test key sorting
Py06 dictionary mapping dictionary nested key does not exist test key sorting
2022-07-06 06:32:00 【River boats listen to the flute in the rain at night】
F1 Dictionaries
1. A dictionary is not a sequence , It's a kind of mapping , A map is also a collection of other objects , But it stores objects through key value pairs rather than relative positions .
2. There is no reliable left to right order in dictionaries , Instead, map keys to values , Form key value pairs .
3. The dictionary is Python The only mapping type among the core data types , With variability .
4. Just like a list , It can be increased or decreased according to the demand .
5. Sets are divided into ordered sets such as lists , Unordered sets are like dictionaries , Easy to remember keys are more suitable when elements in a set are named or marked .
S2 Mapping operations
1. When a dictionary is written literally , Written in braces , And it contains a series of “ key : value ” Yes , Associate keys with values .
2. The dictionary index is the same as the sequence , But the key in square brackets is not the relative position Also note the string ,
>>>A={' Weigong Shiro ':'saber',' Jiantongying ':'rider',' Elia ':'berserker'}
>>>A={' Weigong Shiro ':'saber',' Jiantongying ':'rider',' Elia ':'berserker','time':4}
>>>A[ Elia ]
>>>A[' Elia ']
'berserker'
>>>A['time']+1
5
>>>A
{' Weigong Shiro ': 'saber', ' Jiantongying ': 'rider', ' Elia ': 'berserker', 'time': 4}
>>>A['time']+=1
>>>A
{' Weigong Shiro ': 'saber', ' Jiantongying ': 'rider', ' Elia ': 'berserker', 'time': 5}
+=x The operation is equivalent to A['']=A['']+x , In situ assignment operation proves its variability
It's just A['']+x, Both terms in the formula are invariant
3. Although you can use the literal form of the braces above to build a dictionary , In addition, the new key assignment will create the key , This is contrary to the prohibition of list assignment outside the boundary , Dictionaries allow you to create key value pairs in this way .
>>>A
{' Weigong Shiro ': 'saber', ' Jiantongying ': 'rider', ' Elia ': 'berserker', 'time': 5, ' Wei Gong Chesi ': 'saber'}
4. Dictionaries can be used instead of search operations , Index by using keys , yes Python The fastest way to write a search in ,
5. Another way to create a dictionary , Through to the dict Key value parameter pairs are passed in the type name ( A grammar ), Or pass the sequence of keys and values at run time zip Pair to create a dictionary ( There are four ways to create a dictionary Literal 、 New key assignment 、dict、 dict+zip)
>>>A=dict( Weigong Shiro ='saber', Jiantongying ='rider', Elia = 'berserker')
>>>A
{' Weigong Shiro ': 'saber', ' Jiantongying ': 'rider', ' Elia ': 'berserker'}
>>>A=dict(zip([' Weigong Shiro ',' Jiantongying ',' Elia '],['saber','rider','berserker']))
>>>A
{' Weigong Shiro ': 'saber', ' Jiantongying ': 'rider', ' Elia ': 'berserker'}
Pay attention to dict when The key has no quotation marks , There is no longer a colon in the middle, but an equal sign , Use dict+zip Temporal grammar dict(zip([ list 1],[ List two ])), Because the list is ordered when it is created , So the two lists before and after will correspond to each other and form a key , The first is the key , Value after .
6. A dictionary is essentially an unordered set of key value pairs .
T3 Revisit nested
1. So called key value pair , Values can correspond to more types Such as a dictionary list Numbers etc.
data={'name':{' surname ':' Small ',' name ':' bright '},'job':[' The host ','IT'],'age':40}
>>>data
{'name': {' surname ': ' Small ', ' name ': ' bright '}, 'job': [' The host ', 'IT'], 'age': 40}
ad locum , Used again on the top Three key dictionary ( The keys are “name” “job” and “age” ), however The value is more complex : A nested dictionary acts as name Value , And use a nested list to make by job Value
>>>data['name'][' name ']
' bright '
>>>data['job'][-1]
'IT'
>>>type(data['job'])
<class 'list'>
>>>data['job'].append(' Teachers' ')
>>>data['job']
[' The host ', 'IT', ' Teachers' ']
>>>data
{'name': {' surname ': ' Small ', ' name ': ' bright '}, 'job': [' The host ', 'IT', ' Teachers' '], 'age': 40}
because job A list is a part of a dictionary Separate memory , It is free to increase or decrease , After learning the following dynamic types, we can regard the key reference as a special variable , A variable has no type but a pointer ( I'll talk about it later ).
2. You can see Python The spirit of core data types activity , Embedded Sets allow complex information structures to be built directly and easily , All this It's automatic One The line expression creates The whole nested object structure .
3.
The underlying language
When we no longer need this object
You must carefully free up all object space
Python in , When the object is referenced for the last time ( for example Assign this variable with other values ), This object Occupied by The memory space of will be cleaned up automatically ( Related to the reference counting section ( I'll talk about it later ))
4.
>>>data
{'name': {' surname ': ' Small ', ' name ': ' bright '}, 'job': [' The host ', 'IT', ' Teachers' '], 'age': 40}
>>>data=0
At this time, we restate ,data Variables change from the original dictionary to numbers 0, Previous dictionary objects will be python The garbage collection mechanism automatically cleans up , In fact, immutable types are generally not cleaned up immediately , It's similar to putting it in a special queue for reuse .
F4 Keys that don't exist :if test
1. The dictionary only supports passing Key access object
Although we can pass Assign a value to the new key to expand the dictionary , Accessing a nonexistent key value is still an error
When we write programs, we don't always know what keys currently exist . under these circumstances
One trick is to test before that
Dictionary in Relational expressions allow us to query dictionaries Whether a key exists in
And can pass through Python Of if Statement to branch the query results
>>>data={'name': {' surname ': ' Small ', ' name ': ' bright '}, 'job': [' The host ', 'IT', ' Teachers' '], 'age': 40}
' Xiaohong 'in data
False
>>>if 'name'in data:
...print(data['name'])
{' surname ': ' Small ', ' name ': ' bright '}
If you have more than one action in a statement block to perform
You just need to indent them the same
It can not only enhance the readability of the code , It can also reduce what you want Characters entered
2.
except in test
There are many other ways to avoid getting nonexistent keys in the dictionary we create
get Method
as well as if/else Ternary expression ( In essence, it is a crowded line if sentence )
>>>x=data.get('i',0)
>>>x
0
>>>y=data.get('name',0)
>>>y
{' surname ': ' Small ', ' name ': ' bright '}
>>>z=data['name']if'name'in data else 0
>>>z
{' surname ': ' Small ', ' name ': ' bright '}
This one at the back if Is the sentence similar to the postpositive attribute in English
F5 Key ordering :for loop
1. Because the word Classics are not sequences
They don't contain any reliable left to right order
Print it out , Its keys may be in a different order than they were entered appear
2. If I'm in a dictionary element We really need to emphasize some order
The solution is through Dictionary keys Method to collect a list of keys
Use List sort Method to sort
And then use Python Of for Cycle through the results one by one
x=list(data.keys())
x
['name', 'job', 'age']
for y in x:
print(data[y])
{' surname ': ' Small ', ' name ': ' bright '}
[' The host ', 'IT', ' Teachers' ']
40
Used list() after , We created a list with only keys , The left and right relative order of the list is fixed , It's also variable , We can change it to the order we need , Then output the corresponding value according to this key sequence
Our example The actual effect is In the order of ordered keys , Print the keys and values of this dictionary, which itself is unordered .
3.for loop It's not just sequence operations , They are iterative operations
边栏推荐
- Black cat takes you to learn UFS protocol Chapter 4: detailed explanation of UFS protocol stack
- 基于JEECG-BOOT制作“左树右表”交互页面
- D - How Many Answers Are Wrong
- org.activiti.bpmn.exceptions.XMLException: cvc-complex-type.2.4.a: 发现了以元素 ‘outgoing‘ 开头的无效内容
- 电子书-CHM-上线CS
- Redis core technology and basic architecture of actual combat: what does a key value database contain?
- 国产游戏国际化离不开专业的翻译公司
- 生物医学英文合同翻译,关于词汇翻译的特点
- Lecture 8: 1602 LCD (Guo Tianxiang)
- 模拟卷Leetcode【普通】1447. 最简分数
猜你喜欢
How to do a good job in financial literature translation?
Luogu p2089 roast chicken
Defense (greed), FBI tree (binary tree)
[Tera term] black cat takes you to learn TTL script -- serial port automation skill in embedded development
How much is the price for the seal of the certificate
Address bar parameter transmission of list page based on jeecg-boot
[web security] nodejs prototype chain pollution analysis
Summary of leetcode's dynamic programming 4
How to translate biomedical instructions in English
E - food chain
随机推荐
Redis core technology and basic architecture of actual combat: what does a key value database contain?
Technology sharing | common interface protocol analysis
Remember the implementation of a relatively complex addition, deletion and modification function based on jeecg-boot
Data type of MySQL
翻译生物医学说明书,英译中怎样效果佳
Address bar parameter transmission of list page based on jeecg-boot
B - The Suspects
JWT-JSON WEB TOKEN
Oscp raven2 target penetration process
SourceInsight Chinese garbled
Convert the array selected by El tree into an array object
Simulation volume leetcode [general] 1219 Golden Miner
Chinese English comparison: you can do this Best of luck
Resttemplate and feign realize token transmission
Today's summer solstice
[Tera term] black cat takes you to learn TTL script -- serial port automation skill in embedded development
Use shortcut LNK online CS
keil MDK中删除添加到watch1中的变量
Luogu p2089 roast chicken
How much is the price for the seal of the certificate