12 examples of mastering Python dictionary

examples mastering python dictionary


author |Soner Yıldırım compile |VK source |Towards Data Science

Data structures are a key part of any programming language . In order to create robust and good performance products , You have to be very aware of the data structure .

In this article , We will study Python An important data structure of programming language , Dictionary .

A dictionary is an unordered set of key value pairs . Each item has a key and a value . A dictionary can be seen as a list with a special index .

The key must be unique and immutable . We can use strings 、 Numbers (int or float) Or tuples as keys . Values can be of any type .

Consider a case where we need to store student grades . We can store them in dictionaries or lists .

Using a dictionary allows us to provide students' names by (key) To get every student's grade . On the other hand , In order to get a student's grade , We need an extra list .

The new list contains the names of the students , And in exactly the same order as the score list .

therefore , In this case , Dictionaries are better than lists .

After a brief introduction , Let's start with examples and delve into dictionaries . These examples will cover the features of dictionaries , And the functions and methods that operate on them .

1. Create a dictionary

We can provide 0 Key value pairs to create a dictionary .

empty_dict = {}
grades = {'John':'A', 'Emily':'A+', 'Betty':'B', 'Mike':'C', 'Ashley':'A'}
grades
{'Ashley': 'A', 'Betty': 'B', 'Emily': 'A+', 'John': 'A', 'Mike': 'C'}

2. Access value

We access the values in the list by providing an index . Similarly , In the dictionary , Access values by using keys .

grades['John']
'A'
grades.get('Betty')
'B'

3. Access all values or all keys

keys Method is used to get all the keys .

grades.keys()
dict_keys(['John', 'Emily', 'Betty', 'Mike', 'Ashley'])

The return object is dict_keys object , It is iterable type . therefore , We can do it in for Iterate it in a loop .

Similarly ,values Method returns all values .

grades.values()
dict_values(['A', 'A+', 'B', 'C', 'A'])

We can't be right about dict_keys or dict_values Index operation , But we can turn them into a list , And then use the index .

list(grades.values())[0]
'A'

items Method returns key value pairs .

grades.items()
dict_items([('John', 'A'), ('Emily', 'A+'), ('Betty', 'B'), ('Mike', 'C'), ('Ashley', 'A')])

4. Update or add items

The dictionary is changeable , So we can update 、 Add or delete entries . The syntax for updating or adding items is the same . If there is a given key in the dictionary , Update the value of the existing item . otherwise , A new item will be created ( That is, key value pairs ).

grades['Edward'] = 'B+'
grades['John'] = 'B'
grades
{'Ashley': 'A',
'Betty': 'B',
'Edward': 'B+',
'Emily': 'A+',
'John': 'B',
'Mike': 'C'}

5. Update with a new dictionary

We can also pass the dictionary to update function . The dictionary will be updated according to the items in the new dictionary . For example, it would be clearer .

Consider the following Dictionary :

grades = {'John':'A', 'Emily':'A+', 'Betty':'B', 'Mike':'C'}
grades_new = {'John':'B', 'Sam':'A', 'Betty':'A'}

If we based on grades_new to update grades ,John and Betty The value of will also be updated . Besides , New items will also be added ('Sam':'a').

grades.update(grades_new)
grades
{'Betty': 'A', 'Emily': 'A+', 'John': 'B', 'Mike': 'C', 'Sam': 'A'}

6. Delete the item

We can use del or pop Function delete item . We only pass the key of the item to be deleted .

del(grades['Edward'])
grades.pop('Ashley')
'A'
grades
'Betty': 'B', 'Emily': 'A+', 'John': 'B', 'Mike': 'C'}

And del Functions are different ,pop Function returns the value of the deleted item . therefore , We can choose to assign it to a variable .

7. Dictionary as iterable

We can iterate over the dictionary . By default , Iterations are based on keys .

for i in grades:
print(i)
John
Emily
Betty
Mike

We can also iterate over values (grades.values() or grades.items()).

8. Dictionary generative

It's similar to list generation . Dictionary generation is based on iterables How to create a dictionary of .

{x: x**2 for x in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{word: len(word) for word in ['data','science','is','awesome']}
{'awesome': 7, 'data': 4, 'is': 2, 'science': 7}

iterable The elements in the dictionary become the keys of the dictionary . These values are determined from the assignments in the dictionary generation .

9. Create a dictionary from a list

We can use lists or tuple lists to create dictionaries .

a = [['A',4], ['B',5], ['C',11]]
dict(a)
{'A': 4, 'B': 5, 'C': 11}
b = [('A',4), ('B',5), ('C',11)]
dict(b)
{'A': 4, 'B': 5, 'C': 11}

10. From dictionaries to data frames

Pandas Of dataframe Function can be used to create data frames using a dictionary . The key becomes the column name , Value becomes line .

up to now , We've done some examples with dictionaries with values of strings . however , The values in the dictionary can be of any type , For example, a list of 、numpy Array 、 Other dictionaries and so on .

In the case of creating data frames from a dictionary , Values consist of arrays ( for example list、numpy array).

import numpy as np
import pandas as pd
dict_a = {'names':['Amber','John','Edward','Emily'],
'points':np.random.randint(100, size=4)}
df = pd.DataFrame(dict_a)
df

11.len and clear

len Function returns the number of entries in the dictionary ( The length of the ).clear Method is used to delete all entries in the dictionary , So we're going to get an empty dictionary .

len(grades)
4
grades.clear()
len(grades)
0

12. Copy dictionary

grades = {'John':'A', 'Emily':'A+', 'Betty':'B'}
dict1 = grades
dict2 = grades.copy()
dict3 = dict(grades)

all dict1、dict2 and dict3 Both contain the same key value pairs as the fraction . However ,dict1 It's just a point to grades The pointer to . therefore ,grades Any change in the will change dict1.

dict2 and dict3 It's a separate object in memory , So they don't get grades The impact of change .

We need to pay special attention to how we copy dictionaries .

benefits : Use python3.9 Merge and update operators

Python3.9 Provides a dictionary with merge(“|”) and update(“|=”) Operator . I haven't installed Python 3.9, So I'm going to use Python Examples in documentation :

>>> x = {"key1": "value1 from x", "key2": "value2 from x"}
>>> y = {"key2": "value2 from y", "key3": "value3 from y"}
>>> x | y
{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}
>>> y | x
{'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'}

The dictionary is Python Very important data structure in , In many cases . Our examples in this article will cover most of the dictionaries you need to know .

However , Of course, there are more techniques . Like any other skill , Practice makes perfect , You will master it in practice .

Link to the original text :https://towardsdatascience.com/12-examples-to-master-python-dictionaries-5a8bcd688c6d

Welcome to join us AI Blog station : http://panchuang.net/

sklearn Machine learning Chinese official documents : http://sklearn123.com/

Welcome to pay attention to pan Chuang blog resource summary station : http://docs.panchuang.net/

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

  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