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.co...
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/