Python-Dictionary Foundation-Learning Log-CSDN21 Day Learning Challenge-More Learning Please look forward to the next issue

Catalog

1. Dictionary Concepts

1. Concepts:

2. The format is:

3. Simple examples:

2. Dictionary-related operations

1. Dictionary Creation

a. Direct creation: (simple and rough)

b. Borrowing dict to create

c. Create dictionary objects from zip()

d. fromkeys creates a dictionary from a list of one-dimensional keys

2. Dictionary Access

a. Get'value'by [key]

b. It is better to get the value by get().

List all keys and values

d. List the number of key-value pairs to check if a key exists

3. Dictionary Additions and Deletions

Additions and changes:

a. a['key']='value'==>direct dispatch

        b.   a.update(b) 

c. Detect dictionary keys or increase key-value pairs by setdefault

Delete:

a. del(a['key']) delete directly

b. pop(a['key']) Deletes key-value pairs and returns a value;

c. clear() Delete all key-value pairs

        d. popitem() :

4. Dictionary traversal:

Ending:

Activity address: CSDN 21-day Learning Challenge

The biggest reason for learning is to get rid of mediocrity and have a better life one day earlier. One day later is another day of mediocrity. Dear friends, if you:
Want to systematically/thoroughly learn a technical knowledge point...
It is difficult for a person to insist on learning by groping and trying to organize a group to study efficiently.
Want to blog but can't get started, need to write dry goods to inject energy.
I love writing and am willing to make myself a better person.
 

1. Dictionary Concepts

1. Concepts:

In Python, a dictionary is simply something enclosed in curly braces with key-value pairs.

2. The format is:

{'Key 1':'Value 1','Key 2':'Value 2','Key 3':'Value 3'}

Explanation citing the novice bird tutorial:

Dictionaries are another variable container model and can store any type of object.

Each key:value pair of the dictionary is colon: split, comma between each key-value pair, split, and the entire dictionary is enclosed in curly brackets {}.

3. Simple examples:

a = { 'School_class':2 ,'name':'SYW','age':20,'School':'SZschool','Youlike':'Basketball'}
#This is a dictionary that prints directly:
print(a)

# Here is the output
>>> {'School_class': 2, 'name': 'SYW', 'age': 20, 'School': 'SZschool', 'Youlike': 'Basketball'}

2. Dictionary-related operations

1. Dictionary Creation

There are many ways to create dictionaries. Here's an introduction.

a. Direct creation: (simple and rough)

dd = {'name':'SYW','age':21,'job':'student'}
cc = {}   #Empty Dictionary Object
print(dd,cc)

Output:

>>> {'name': 'SYW', 'age': 21, 'job': 'student'} {}

b. Borrowing dict to create

z = dict(name='SYW',age=21,job='student')
v = dict([("name","SYW"),("age",21)])
dit0 = dict()   #Empty Dictionary Object
print(z,v,dit0)

Output:

>>> {'name': 'SYW', 'age': 21, 'job': 'student'} {'name': 'SYW', 'age': 21} {}

c. Create dictionary objects from zip()

Advantage: Separate key-value pairs, create lists, and create flexible formats.

Suggestion: Keys and values should be imported one-to-one, or keys will be discarded after they are created.

f = ['name','age','job']
s = ['SYW',21,'Student']
dit0 = dict(zip(f,s))
print(dit0)

Output:

>>> {'name': 'SYW', 'age': 21, 'job': 'Student'}

d. fromkeys creates a dictionary from a list of one-dimensional keys

# 1. Dictionaries with an empty default value (None)
list1 = ['name','age','job']
a = dict.fromkeys(list1)
print(a)

Output:
>>> {'name': None, 'age': None, 'job': None}

# 2. Change the default to any value and create a dictionary:
list1 = ['name','age','job']
b = dict.fromkeys(list1,"Han Dynasty" )
print(b)

Output:
>>> {'name': 'Han Dynasty', 'age': 'Han Dynasty', 'job': 'Han Dynasty'}

 

2. Dictionary Access

Create a root dictionary to provide access to the corresponding method functions.

a = {'name':'SYW','age':18,'job':'student'}

a. Get'value'by [key]

print(a['name'])
print(a['age'])
# Keys that do not exist throw exceptions.
# The exception part was replaced by try...except...so no exception was thrown and the output "Error! The key'sex'does not exist!" when an exception occurs.
try:
    print(a['sex'])
except Exception as e:
    print("Report errors! key'sex'Non-existent!")

Output:
>>> SYW
>>> 18
>>> Report errors! key'sex'Non-existent!

b. It is better to get the value by get().

Function: key exists, return value; Key does not exist, returns None or default object.

print(a.get('name'))
print(a.get('sex'))
print(a.get('sex','One Man'))  # If the key does not exist, go back to'a man'
 # List all key-value pairs
print(a.items())

Output:
>>> SYW
>>> None
>>> One Man
>>> dict_items([('name', 'SYW'), ('age', 18), ('job', 'student')])

List all keys and values

# List all keys
print(a.keys())
# List all values
print(a.values())

Output:
>>> dict_keys(['name', 'age', 'job'])
>>> dict_values(['SYW', 18, 'student'])

d. List the number of key-value pairs to check if a key exists

# Number of len() key-value pairs
print('The number of key-value pairs is:',len(a))
# Detect if a key is in a dictionary
a = {"name":"SYW","age":18}
print("name" in a)

Output:
>>> The number of key-value pairs is: 3
>>> True

 

3. Dictionary Additions and Deletions

Additions and changes:

a. a['key']='value'==>direct dispatch

Keys exist ==>Overwrite old key values;
Keys do not exist =>Add a new key-value pair. (

a = {'name':'SYW','age':21,'job':'SZstudent'}
a['address']='Shantou Professional Street'
a['age']=19
print(a)

Output:
>>> {'name': 'SYW', 'age': 19, 'job': 'SZstudent', 'address': 'Shantou Professional Street'}

        b.   a.update(b) 

Plug all the key values of b into a and override the values of the same key of a directly.

dict0={'name':'SYW','salary':'18w'}
dict1={'name':'xiaolin','city':'guangdong'}
dict1.update(dict0)
print(dict1)

Output:
>>> {'name': 'SYW', 'city': 'guangdong', 'salary': '18w'}

c. Detect dictionary keys or increase key-value pairs by setdefault

A=['name','age']
B=['SYW',20]
dict0 = dict(zip(A,B))
print(dict0)
dict0.setdefault('name','XL')
# Since name exists, the value of name does not change.
print(dict0)
dict0.setdefault('city','guangdong')
# Because ciy does not exist, a new key-value pair is added.
print(dict0)

Output:
>>> {'name': 'SYW', 'age': 20}
>>> {'name': 'SYW', 'age': 20}
>>> {'name': 'SYW', 'age': 20, 'city': 'guangdong'}

Delete:

a. del(a['key']) delete directly

b. pop(a['key']) Deletes key-value pairs and returns a value;

c. clear() Delete all key-value pairs

a = {'name':'SYW','age':20,'job':'Student'}
del(a['name'])
print(a)
b = a.pop('age')
print(b)
a.clear()
try:
    print(a['job'])
except Exception as e:
    print("Dictionaries a Has been cleared~")

Output:
>>> {'age': 20, 'job': 'Student'}
>>> 20
>>> Dictionaries a Has been cleared~

        d. popitem() :

Delete and return the last key-value pair.

a = {'name':'SYW','age':21,'job':'Student'}
print(a)
print(a.popitem())
print(a)
print(a.popitem())
print(a)

Output:
>>> {'name': 'SYW', 'age': 21, 'job': 'Student'}
>>> ('job', 'Student')
>>> {'name': 'SYW', 'age': 21}
>>> ('age', 21)
>>> {'name': 'SYW'}

4. Dictionary traversal:

Key traversal, value traversal, and key-value traversal:

A=['name','age']
B=['SYW',20]
dict0 = dict(zip(A,B))

for key in dict0:
    print("The dictionary keys are:",key)
print("-------------")
for value in dict0:
    print("Dictionary value traversal:",value)
print("-------------")
for key,value in dict0.items():
    print("The key of the dictionary is{0},Value is{1}. ".format(key,value))
print("-------------")


Output:
>>> The dictionary keys are: name
>>> The dictionary keys are: age
>>> -------------
>>> Dictionary value traversal: name
>>> Dictionary value traversal: age
>>> -------------
>>> The key of the dictionary is name,Value is SYW. 
>>> The key of the dictionary is age,The value is 20.
>>> -------------

Ending:

That's all the more basic operations of the dictionary. Please read the official documents for more detailed operations.

Tags: Python

Posted by MaxD on Tue, 20 Sep 2022 22:38:59 +0530