# day5__ (Dictionary, addition, deletion, modification, and nesting of dictionaries)

Posted by JD* on Thu, 18 Jun 2020 09:11:13 +0200

# 1, Dictionary

Disadvantages of list: 1) a large amount of data can be stored in the list, but the correlation between data is not strong; 2) the query speed of the list is relatively slow

Container data type: dict

Classification by variable and immutable data types:

Immutable (hashable) data types: int, str, bool (Boolean), tuple (tuple).
Variable (non hashable) data types: list, dict, set.

Dictionary: {}, container data type stored as key value pair:

```dic = {'Zhang San':   #Key value pair
{'name': 'Zhang Si', 'age': 18, 'sex': 'male'},
'catr':   #Key value pair
['Daniel', 'Carola', 'overbearing']
}
print(dic)
```

Note:

• Key must be immutable data type: int,str, value can be any data type and object, unique.
• Dictionary before 3.5 (including 3.5) is unordered
• Dictionary 3.6x will be arranged in the order of the first dictionary
• Dictionary 3.7 is orderly.

Disadvantages of Dictionary: space for time

Advantages of Dictionary: very fast query speed, storage of related data

### 1. Dictionary creation

Method 1:

```dic = dict((('one',1),('two',2),('three',3)))
print(dic)
//Output results: {'one': 1,'two': 2,'three': 3}
```

Method 2:

```dic = dict(one=1, two=2, three=3)
print(dic)
//Output result: {'one': 1, 'two': 2, 'three': 3}
```

Method 3:

```dic = dict({'one': 1, 'two': 2, 'three': 3})
print(dic)
//Output result: {'one': 1, 'two': 2, 'three': 3}
```

### 2. Increase

Directly increase by key value pair

```dic = {'name': 'mrxiong', 'age': 18}
dic['weight'] = 75 # Without weight, increase the key value pair
print(dic)     # {'name': 'mrxiong', 'age': 18, 'weight': 75}
dic['name'] = 'barry' # With the name key, it becomes the dictionary change value
print(dic)    # {'name': 'barry', 'age': 18, 'weight': 75}
```

setdefault

```dic = {'name':'mrxiong','age':30,}
print(dic)

dic.setdefault('name','barry')  # With this key, it will not change
print(dic)

#It has a return value
dic = {'name': 'Taibai', 'age': 18}
ret = dic.setdefault('name')
print(ret)  # Taibai
```

### 3. Delete

pop deletes the key value pair of the dictionary through the key. If there is a return value, you can set the return value.

```dic = {'name':'mrxiong','age':30,}
ret = dic.pop('name')  #With return value
print(dic)
```

When we don't know whether there is a key value in the dictionary, we can implement it through pop. If there is no key value, we will not delete the dictionary and return the set parameter prompt

```dic = {'name':'mrxiong','age':30,}
ret = dic.pop('abcc','No such key')  #With return value
print(ret)
print(dic)
```

clear() clear

```dic = {'name':'mrxiong','age':30,}
dic.clear()
print(dic)
```

del

Delete key value pair by key

```dic = {'name':'mrxiong','age':30,}
del dic['name']
print(dic)
```

### 4. Change

Direct change by key value pair

```dic = {'name': 'mrxiong', 'age': 30}
dic['name'] = 'barry'
print(dic)
//Output results:
{'name': 'barry', 'age': 30}
```
```dic = {'name': 'mrxiong', 'age': 30}
dic.update(ses='male',height=175)
print(dic)
//Output results:
{'name': 'mrxiong', 'age': 30, 'ses': 'male', 'height': 175}
```
```dic = {'name': 'mrxiong', 'age': 30}
dic.update(name='barry')
print(dic)
//Output results:
{'name': 'barry', 'age': 30}
```
```dic = {'name': 'mrxiong', 'age': 30}
dic.update([('one', 1), ('two', 2)])
print(dic)
//Output results:
{'name': 'mrxiong', 'age': 30, 'one': 1, 'two': 2}
```

### 5. Check

get

```dic = {'name': 'mrxiong', 'age': 30, 'hobby_list': ['Straight man', 'drive a car', 'play']}
v = dic.get('hobby_list')
print(v)
//Output results: ['straight man', 'driving', 'playing']

dic = {'name': 'mrxiong', 'age': 30, 'hobby_list': ['Straight man', 'drive a car', 'play']}
v = dic.get('name')
print(v)
//Output: mrxiong

dic = {'name': 'mrxiong', 'age': 30, 'hobby_list': ['Straight man', 'drive a car', 'play']}
v = dic.get('nameone')
print(v)
//Output result: None

dic = {'name': 'mrxiong', 'age': 30, 'hobby_list': ['Straight man', 'drive a car', 'play']}
v = dic.get('nameone','No such key')    #Return value can be set
print(v)
//Output result: no such key
```

### 6. Three special operations

```keys()
dic = {'name': 'Taibai', 'age': 18}
print(dic.keys()) # dict_keys(['name', 'age'])

values()
dic = {'name': 'Taibai', 'age': 18}
print(dic.values()) # dict_values(['Too white ', 18])

items()
dic = {'name': 'Taibai', 'age': 18}
print(dic.items()) # dict_items([('name ',' too white '), ('age', 18)])
```

#### Exercises:

dic = {'k1': "v1", "k2": "v2", "k3": [11,22,33]}

```dic = {'k1': "v1", "k2": "v2", "k3": [11, 22, 33]}
dic['k4']='v4'
print(dic)
```
```dic = {'k1': "v1", "k2": "v2", "k3": [11, 22, 33]}
dic.setdefault('k4', 'v4')
print(dic)
```

Please output the modified dictionary with the value of "alex" corresponding to "k1" in the modified dictionary

```dic = {'k1': "v1", "k2": "v2", "k3": [11, 22, 33]}
dic['k1']='alex'
print(dic)
```
```dic = {'k1': "v1", "k2": "v2", "k3": [11, 22, 33]}
dic.update(k1='alex')
print(dic)
```

Add an element 44 to the corresponding value of k3 to output the modified dictionary

```dic = {'k1': "v1", "k2": "v2", "k3": [11, 22, 33]}
dic["k3"].append(44)
print(dic)
```

Please change 22 to 'apple' in the value corresponding to k3, and output the modified dictionary

```dic = {'k1': "v1", "k2": "v2", "k3": [11, 22, 33]}
dic['k3'][2] = 'apple'
print(dic)
```

Please insert element 18 at the first position of the value corresponding to k3, and output the modified dictionary

```dic = {'k1': "v1", "k2": "v2", "k3": [11, 22, 33]}
dic['k3'].insert(1, 18)
print(dic)
```

# 2, Nesting of dictionaries

dic = {'k1': "v1", "k2": "v2", "k3": [11,22,33]}

Add an element 44 to the corresponding value of k3 to output the modified dictionary

```dic = {'k1': "v1", "k2": "v2", "k3": [11, 22, 33]}
dic["k3"].append(44)
print(dic)
```

practice:

```dic = {
'name': 'Wang Feng',
'age': 48,
'wife': [{'name': 'International chapter', 'age': 38}],
'children': {'girl_first': 'Small apple', 'girl_second': 'Xiaoyi', 'girl_three': 'Zenith'}
}
```

1) get the name of Wang Feng.

```name = dic['name']
print(name)    #Wang Feng
```

2] get the dictionary: {'name': 'international chapter', 'age':38}.

```l1 = dic['wife']  # Get this list first
di = l1[0]  # The dictionary is the first element of the list. Therefore, the dictionary is obtained through the index
print(di)
```

Optimization:

```l1 = dic['wife'][0]
print(l1)   #{'name': 'international chapter', 'age': 38}
```

3) get the name of Wang Feng's wife.

```di = dic['wife'][0]  # This is the code of the small dictionary obtained from the last question
wife_name= di['name']  # You can get the corresponding value through the small dictionary and then through the key
print(wife_name)
```

Optimization:

```l3 = dic['wife'][0]['name']
print(l3)
```

4) get Wang Feng's third child's name.

```dic2 = dic['children']  # Get this dictionary first
name = dic2['girl_three']  # Get the name of the third child through this dictionary
print(name)
```

Optimization:

```l2 = dic['children']['girl_three']
print(l2)   #Zenith
```

Topics: Python