python learning notes -- dictionary operation

Posted by renzaho on Thu, 02 Apr 2020 02:54:11 +0200

1 create dictionary

person = {'name':'fmxd', 'age':1, 'sex':'boy'}

2 operation dictionary

2.1 obtaining data

age = person['age']

2.2 add attribute

person[food] = 'milk'

2.3 modifying attribute values

father = {}
father['name'] = 'fxd'
father['age'] = 25
father['sex'] = 'male'

2.4 deleting attribute values

del person['age']

3 traversal dictionary

3.1 traversal key value pair

for key, value in person.items():
    #doSomeThing with key or value

3.2 traversal key

for key in person.keys():
    #doSomeThing with key

Note: it is not necessary to sort when obtaining. The following code can be used for sorting
for key in sorted(person.keys()):

3.3. Traversal value

for value in person.values():
    #doSomeThing with value

4 nesting

4.1 dictionary nested list

The format is as follows

map = {'key1':[list1], 'key2':'value2', ...}

4.2 list nested dictionary

The format is as follows

list = [map1, map2, map3 ...]

4.3 dictionary nesting dictionary

The format is as follows

map = {'key1':map1, 'key2':map2 ...}

5 Practice

Code

#import this
#Create a dictionary
person = {'name':'fmxd', 'age':3, 'sex':'boy'}
print('The child is a '+ person['sex'] + ',he is '+ str(person['age']) + ' years old ,and his name is '+ person['name'] + '.')
#Add attribute
person['food'] = 'milk'
print('His favorite food is ' + person['food'] + '.')
#Modify property value
father = {}
father['name'] = 'fxd'
father['age'] = 25
father['sex'] = 'male'
person['father'] = father['name']
print('His father is '+ father['name'] + ',he is '+ str(father['age']) + ' years old last year.')
father['age'] = 26
print('And this year Mr.fxd is '+ str(father['age']) + ' years old.')
#Delete property value
del person['age']
print('Let us make the boy' + '\'' + 's age is a ecret:')
print(str(person) + '.')
#Ergodic dictionary
#Traversal key value pair
mother = {}
mother['name'] = 'hfx'
mother['age'] = 25
mother['sex'] = 'female'
person['mother'] = mother['name']
for key, value in mother.items():
    print('His mother' + '\'' + key + ' is ' + str(value))
#Ergodic key
for key in father.keys():
    print('His father' + '\'' + key + ' is ' + str(father[key]))
#nesting
family = [person, father, mother]
print('The happy family is')
print(family)

output

The child is a boy,he is 3 years old ,and his name is fmxd.
His favorite food is milk.
His father is fxd,he is 25 years old last year.
And this year Mr.fxd is 26 years old.
Let us make the boy's age is a ecret:
{'name': 'fmxd', 'sex': 'boy', 'food': 'milk', 'father': 'fxd'}.
His mother'name is hfx
His mother'age is 25
His mother'sex is female
His father'name is fxd
His father'age is 26
His father'sex is male
The happy family is
[{'name': 'fmxd', 'sex': 'boy', 'food': 'milk', 'father': 'fxd', 'mother': 'hfx'}, {'name': 'fxd', 'age': 26, 'sex': 'male'}, {'name': 'hfx', 'age': 25, 'sex': 'female'}]

Topics: Attribute