Simple operation of python Dictionary (modify, delete, nest, traverse, copy)

1, Python dictionary

A dictionary is another variable container model and can store any type of object.

Each key value key = & gt; value pair of the dictionary is divided by colon: comma is used between each key value pair, and the whole dictionary is included in curly bracket {}, with the format as follows:

d = {key1 : value1, key2 : value2 }

The key is generally unique. If the last key value pair is repeated, the previous one will be replaced. The value does not need to be unique.

>>>dict = {'a': 1, 'b': 2, 'b': '3'}
>>> dict['b']
'3'
>>> dict
{'a': 1, 'b': '3'}

Value can take any data type, but the key must be immutable, such as string, number or tuple.

1, example

# Data type of python: Dictionary

# Data types associated with variables
name = 'bily'
num = 89
key = 88.8
list = [3,4,5,6]
tuple = (6,4,68)

# Examples of dictionaries: keys and values
dict = {'name':'Old week','age':'29','job':'Programmer'}
print(dict)
dict1={1:101,2:102}
print(dict1)
Output result of the above example:
{'name': 'Old week', 'age': '29', 'job': 'Programmer'}
{1: 101, 2: 102}

Tables and tuples can be written directly into values, while dictionaries need keys and values.

2. Simple dictionary operation

# Define a dictionary
dict2 = {
    'Hebei':'Shijiazhuang',
    'Gansu':'Lanzhou',
    'Sichuan':'Chengdu'
}
print(dict2)

# Access to Dictionary (value) = = > value = name of DICTIONARY [key]
sjz = dict2['Hebei']
print(sjz)

# Add dictionary data (key value pair)
dict2['Shanxi']='Taiyuan'
print(dict2)

# Modify dictionary values
dict2['Hebei']='Xingtai'
print(dict2)

# Delete key value pair of dictionary
del dict2['Sichuan']
print(dict2)
Output result of the above example:
#Original data
 {'Hebei': 'Shijiazhuang', 'Gansu': 'Lanzhou', 'Sichuan': 'Chengdu'}

#Access key (Hebei)
Shijiazhuang

#Add key value pair ('shanxi ':' Taiyuan ')
{'Hebei': 'Shijiazhuang', 'Gansu': 'Lanzhou', 'Sichuan': 'Chengdu', 'Shanxi': 'Taiyuan'}

#Modify the value of the dictionary (Shijiazhuang to Xingtai)
{'Hebei': 'Xingtai', 'Gansu': 'Lanzhou', 'Sichuan': 'Chengdu', 'Shanxi': 'Taiyuan'}

#Delete key value pair of Dictionary (Sichuan)
{'Hebei': 'Xingtai', 'Gansu': 'Lanzhou', 'Shanxi': 'Taiyuan'}

2, Ergodic dictionary

1. Define a dictionary

dict = {'name':'Old week','age':'29','job':'Programmer'}

# Traversal Dictionary: set of key value pairs, set of keys, set of values

for key,value in dict.items():
    print(key+":"+value)
Output result of the above example:
name:Old week
age:29
job:Programmer

2. Common methods of traversing Dictionaries

print(dict.items())
print(dict.keys())
print(dict.values())
Output result of the above example:
dict_items([('name', 'Old week'), ('age', '29'), ('job', 'Programmer')])
dict_keys(['name', 'age', 'job'])
dict_values(['Old week', '29', 'Programmer'])

3. Number of dictionary elements

print(len(dict))
Output result of the above example:
3

4. Copy dictionary

dict1 = {}
dict1 = dict.copy()
print(dict1)
Output result of the above example:
{'name': 'Old week', 'age': '29', 'job': 'Programmer'}

5. Sort dictionary keys

print(sorted(dict1.keys()))
print(sorted(dict1.values()))

for info in sorted(dict1.keys()):
    print(info,end=" ")

print("\n")
for info in sorted(dict1.keys()):
    print(value,end=" ")
Output result of the above example:
['age', 'job', 'name']
['29 ',' programmer ',' old week ']
age job name 

Programmer programmer 

6. Using functions to get dictionary values

print(dict1.get('age'))
Output result of the above example:
29

7. How to delete a dictionary

# Delete dictionary
# dicr1.clear()
dict = {'name':'Old week','age':'29','job':'Programmer'}
print(dict)

# Delete end
#print(dict.popitem())
#print(dict)

# Delete specified
print(dict.pop('age'))
print(dict)
Output result of the above example:
{'name': 'Old week', 'age': '29', 'job': 'Programmer'}
29
{'name': 'Old week', 'job': 'Programmer'}

8. Small exercises

(1) Write a dictionary to check whether the given key already exists in the dictionary.

dict = {
    'name':'xgp',
    'ah':'sleep',
    'yd':'pb',
}
print(dict)
Output result of the above example:
{'name': 'xgp', 'ah': 'sleep', 'yd': 'pb'}

(2) Write a Python program to add an existing dictionary to an empty dictionary.

dict1 = {}
dict1 = dict.copy()
print(dict1)
Output result of the above example:
{'name': 'xgp', 'ah': 'sleep', 'yd': 'pb'}

(3) Write a dictionary, traverse all the key, value, key value pairs of the dictionary.

dict2 = {
    '1':'1',
    '2':'2',
    '3':'3',
    '4':'4',
    '5':'5'
}
print(dict2.keys())
print(dict2.values())
print(dict2.items())
Output result of the above example:
dict_keys(['1', '2', '3', '4', '5'])
dict_values(['1', '2', '3', '4', '5'])
dict_items([('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5')])

3, Nesting of dictionaries and lists

1. Define a dictionary

dict = {'name':'Old week','age':'29','job':'Programmer'}
dict1 = {'name':'Old week','age':'29'}
dict2 = {'age':'29','job':'Programmer'}
print(dict,dict1,dict2)
Output result of the above example:
{'name':'Old week','age':'29','job':'Programmer'},{'name':'Old week','age':'29'},{'age':'29','job':'Programmer'}

2. Nested dictionary in list

list = [dict,dict1,dict2]
print(list)
Output result of the above example:
[{'name': 'Old week', 'age': '29', 'job': 'Programmer'}, {'name': 'Old week', 'age': '29'}, {'age': '29', 'job': 'Programmer'}]
{'pet': ['cat', 'dog', 'duck']}

3. Nested list in dictionary

dict3 ={'pet':['cat','dog','duck']}
print(dict3)
Output result of the above example:
{'pet': ['cat', 'dog', 'duck']}

4. Dictionary nested in dictionary

dict4 = {
    'age':{'gir1':'18','boy':'20'},
    'job':{'man':'IT','women':'db'}
}
print(dict4)

for key, value in dict4.items():
    print('key:'+key,end=" ")
    for v in value.items():
        print(v)
Output result of the above example:
{'age': {'gir1': '18', 'boy': '20'}, 'job': {'man': 'IT', 'women': 'db'}}
key:age ('gir1', '18')
('boy', '20')
key:job ('man', 'IT')
('women', 'db')

4, Small test

1. Create two dictionaries to represent the teacher, and then store them in a list called person. Traverse the list and print out the information of each teacher.

(1) Create two dictionaries to represent teachers

dict = {
    'name':'xgp',
    'age':'18',
    'job':'Programming teacher'
}
dict1 = {
    'name':'wsd',
    'age':'20',
    'job':'Operation and maintenance teacher'
}
print(str(dict)+str(dict1))
Output result of the above example:
{'name': 'xgp', 'age': '18', 'job': 'Programming teacher'}{'name': 'wsd', 'age': '20', 'job': 'Operation and maintenance teacher'}

(2) Two dictionaries are stored in a list called person

person = [dict,dict1]
print(person)
Output result of the above example:
[{'name': 'xgp', 'age': '18', 'job': 'Programming teacher'}, {'name': 'wsd', 'age': '20', 'job': 'Operation and maintenance teacher'}]

(3) Traverse the list and print out the information of each teacher

for key,value in person[0].items():
    print(key+":"+value)

print('\n')
for key,value in person[1].items():
    print(key+":"+value)
Output result of the above example:
name:xgp
age:18
job:Programming teacher

name:wsd
age:20
job:Operation and maintenance teacher

2. Create multiple dictionaries, each with a pet's name; in each dictionary, include the pet's type and owner's name. These dictionaries are stored in a list called pets, and then the list is traversed to print out the pet information.

(1) Create multiple dictionaries, each with a pet's name; in each dictionary, include the pet's type and owner's name.

dog = {
    'dog':'Cokey',
    'type':'Optimistic',
    'master':'xgp',
}
cat = {
    'cat':'Garfield',
    'type':'lively',
    'master':'wsd'
}

bird = {
    'bird':'Parrot',
    'type':'free',
    'master':'dsw'
}
print(dog)
print(cat)
print(bird)
Output result of the above example:
{'dog': 'Cokey', 'type': 'Optimistic', 'master': 'xgp'}
{'cat': 'Garfield', 'type': 'lively', 'master': 'wsd'}
{'bird': 'Parrot', 'type': 'free', 'master': 'dsw'}

(2) Store these dictionaries in a list called pets

pets = [dog,cat,bird]
print(pets)
Output result of the above example:
[{'dog': 'Cokey', 'type': 'Optimistic', 'master': 'xgp'}, {'cat': 'Garfield', 'type': 'lively', 'master': 'wsd'}, {'bird': 'Parrot', 'type': 'free', 'master': 'dsw'}]

(3) Traverse the list and print out the information of pets

for key,value in pets[0].items():
    print(key+":"+value)
print('\n')
for key,value in pets[1].items():
    print(key+":"+value)
print('\n')
for key,value in pets[2].items():
    print(key+":"+value)
Output result of the above example:
dog:Cokey
type:Optimistic
master:xgp

cat:Garfield
type:lively
master:wsd

bird:Parrot
type:free
master:dsw

Tags: Python Programming

Posted on Mon, 16 Mar 2020 01:24:16 -0700 by jokullsolberg