Happy journey of simple Python: Dictionary operation of Python basic syntax

Defonds 2020-11-13 04:52:45
happy journey simple python dictionary



Python The dictionary allows us to store key value pairs . The order of key value pairs in a dictionary is not guaranteed , This is because Python Our dictionary doesn't hold their index .
A simple example of a dictionary is as follows :

myDictionary = {
"pi": 3.14,
"phi": 1.618
}

In this dictionary ,pi and phi It's a key , and 3.14 and 1.618 It's their corresponding value , Thus, a key value pair is formed .
In this paper , We will learn the following : How to create a Python Dictionaries ; How to add and remove elements to a dictionary ; Loop the elements in the dictionary ; And others with sample programs Python Dictionary operation and conversion .

1. Python Dictionary example

stay Python in , Dictionaries are created by braces and key value pairs . A basic Python An example of a dictionary is :

myDictionary = {
"Python": "High Level Programming Language",
"Assembly": "Machine Level Programming Lanugage",
"SciPy": "Python Library for Mathematical and Scientific Calculations"
}

among ,myDictionary Variables hold references to the dictionary , You can use the variable name to access the values in the dictionary , You can also call any field function .

1.1. Print Dictionary

You can use print() Function to print fields to the console . The field will be converted to a string constant and printed .

# Python Example – Print Dictionary
myDictionary = {
"Python" : "High Level Programming Language",
"Assembly" : "Machine Level Programming Language",
"SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
print(myDictionary)

Execution and output :
 Print Dictionary .png

1.2. Check whether the object is dictionary type

You can use type() Function to check whether a dictionary variable is indeed a dictionary type .

# Python Example – Check if it is Dictionary
print(type(myDictionary))

Execution and output :
 Check whether the object is dictionary type .png

2. An example of adding elements to a dictionary

To add an element to an existing dictionary , You can use the key as an index to assign values directly to the dictionary variable .
myDictionary[newKey] = newValue
among myDictionary We need to add key value pairs newKey:newValue The existing index of .

2.1. Add multiple elements to the dictionary

In this example , We are going to add multiple elements to the dictionary .

# create and initialize a dictionary
myDictionary = {
'a' : '65',
'b' : '66',
'c' : '67'
}
# add new items to the dictionary
myDictionary['d'] = '68'
myDictionary['e'] = '69'
myDictionary['f'] = '70'
print(myDictionary)

Execution and output :
 Add multiple elements to the dictionary .png

2.2. Add a single element to the dictionary

In the next example, we initialize a dictionary , Then add a new element of a key value pair to it .

# create and initialize a dictionary
myDictionary = {
"Python" : "High Level Programming Language",
"Assembly" : "Machine Level Programming Language",
"SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
# add new item to the dictionary
myDictionary['Matplotlib'] = 'Python library to draw plots'
print(myDictionary)
print(myDictionary['Matplotlib'])

Execution and output :
 Add a single element to the dictionary .png

3. Dictionary loop traversal

You can use for Loop through a dictionary . Dictionaries can be iterated , So we can use for loop .

# Python Dictionary Loop Example
myDictionary = {
"Python" : "High Level Programming Language",
"Assembly" : "Machine Level Programming Language",
"SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
for item in myDictionary:
print(item)

Execution and output :
 Printed out all the key elements .png
Printed out all the key elements .

3.1. Loop through the keys and values of the dictionary

To get the relevant value , You can use the key you get to get the corresponding value .

# Loop through keys and values of Dictionary
for key in myDictionary:
print(key, myDictionary[key], sep=':')
for key, value in myDictionary.items():
print(key, ':', value)

Execution and output :
 Loop through the keys and values of the dictionary .png

4. Loop through the values of the dictionary

Sometimes you just need to traverse the values in the dictionary , You can use the values() Function to access the values in the dictionary separately , And then use for Loop through these values .

# Loop through Dictionary Values Example
myDictionary = {
"Python" : "High Level Programming Language",
"Assembly" : "Machine Level Programming Language",
"SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
for value in myDictionary.values():
print(value)

Execution and output :
 Loop through the values of the dictionary .png

4.1. Print dictionary values

Dictionary values() Function to return a list object of all values .

# Print Dictionary Values
print(myDictionary.values())

Execution and output :
 Print dictionary values .png

5. Check whether the key exists in the dictionary

To check if a key is in a dictionary , have access to in keyword , Here's a quick example :
isPresent = ‘Python’ in myDictionary
If key Python It exists in the dictionary , return True, Otherwise, return to False.
If the field is named myDictionary, When judging whether a given key exists in the dictionary , We need to consider both positive results ( The key exists ) And negative results ( The key does not exist ).

# Check if Key Exists in Dictionary Example
myDictionary = {
"Python" : "High Level Programming Language",
"Assembly" : "Machine Level Programming Language",
"SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
isPresent = 'Python' in myDictionary
print('Python', 'is present in myDictionary:', isPresent)
isPresent = 'Java' in myDictionary
print('Java', 'is present in myDictionary:', isPresent)

Execution and output :
 Check whether the key exists in the dictionary .png

6. Get dictionary length

To get the length of the dictionary or the number of elements in the dictionary , You can use the standard library len() function . The syntax to get the dictionary length is as follows :
len(myDictionary)
len() It returns the number of key value pairs in the dictionary .

# Dictionary Length Example
myDictionary = {
"Python" : "High Level Programming Language",
"Assembly" : "Machine Level Programming Language",
"SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
length = len(myDictionary)
print('Length of dictionary is', length)

Execution and output :
 Get dictionary length .png

7. Remove specific elements from the dictionary

To remove a key value pair from the dictionary , Using dictionary objects pop() Function and pass the key to it as an argument .

myDictionary.pop(theKey)

among myDictionary It's a dictionary object ,theKey It's the key of the key value pair you want to remove . meanwhile ,pop Function returns the value of the corresponding key value pair .
Besides , You can still use it del Keywords remove a key value pair through a key :

del myDictionary[theKey]

7.1. Use pop() Function to remove elements

In the next example, we create a dictionary , After initialization , Use pop() Function to remove an item .

# Example to pop item from Dictionary using pop() function
myDictionary = {
"Python" : "High Level Programming Language",
"Assembly" : "Machine Level Programming Language",
"SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
poppedItem = myDictionary.pop('SciPy')
print(poppedItem)
print(myDictionary)

Execution and output :
 Use pop() Function to remove elements .png
It can be seen that , Use pop() function , Not only can we remove the key value pair from the dictionary , And we can store the value of the key value pair in a variable .

7.2. Use del Keywords remove elements

Next we will create a dictionary , Initialize it , And then there's going to be del Keyword to remove an item .

# Example to pop item from Dictionary using del keyword
myDictionary = {
"Python" : "High Level Programming Language",
"Assembly" : "Machine Level Programming Language",
"SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
del myDictionary['SciPy']
print(myDictionary)

Execution and output :
 Use del Keywords remove elements .png

8. The dictionary is empty

To empty a dictionary , That is, remove all elements from the dictionary , Using dictionary objects clear() function .

myDictionary.clear()

8.1. An example of emptying a dictionary

In the next example, we create a dictionary , Use multiple key values to initialize elements , And then there's going to be clear() Function to clear it .

# Example to remove all items in a Python Dictionary
myDictionary = {
"Python" : "High Level Programming Language",
"Assembly" : "Machine Level Programming Language",
"SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
print('Dictionary items:\n', myDictionary)
myDictionary.clear()
print('Dictionary items:\n', myDictionary)

Execution and output :
 An example of emptying a dictionary .png

Reference material

版权声明
本文为[Defonds]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database