A detailed summary of the Python dictionary

  • 2020-12-22 17:42:10
  • OfStack

The dictionary (dict) structure is a commonly used data structure in Python. Based on my own practical experience, the author summarizes relevant knowledge of the dictionary in the hope of enlightening the readers

Create a dictionary

A common way to create a dictionary is to create an empty dictionary and then add keys (key) and values (value) one by one. For example, create a dictionary person={'name':'Tome', 'age':22, 'city':'Shanghai ':' 073569'}


person = {}

person['name'] = 'Tom'
person['age'] = 22
person['city'] = 'Shanghai'
person['ID'] = '073569'

print(person)

The output result is:

[

{'name': 'Tom', 'age': 22, 'city': 'Shanghai', 'ID': '073569'}

]

This way of creating is simple and primitive, and the code is not elegant enough. We use the zip function to create this dictionary quickly and easily:


attrs = ['name', 'age', 'city', 'ID']
values = ['Tom', 22, 'Shanghai', '073569']
person = dict(zip(attrs, values))

print(person)

The output is the same as the original code 1.

Through the dictionary

In practical applications, we often need to walk through the dictionary. The implementation method can be referred to the following code:


attrs = ['name', 'age', 'city', 'ID']
values = ['Tom', 22, 'Shanghai', '073569']
person = dict(zip(attrs, values))

for key, value in person.items():
  print('Key:%-6s, Value:%s'%(key, value))

The output result is:

[

Key:name , Value:Tom
Key:age , Value:22
Key:city , Value:Shanghai
Key:ID , Value:073569

]

Swap key value pairs

In practical applications, sometimes we need to look up the key corresponding to a value (value) in the dictionary, walking through the dictionary is one option, and swapping key-value pairs is another. The implementation code of the key-value pair is as follows:


attrs = ['name', 'age', 'city', 'ID']
values = ['Tom', 22, 'Shanghai', '073569']
person = dict(zip(attrs, values))

print(' Before the switch: ')
print(person)

Person = {v:k for k,v in person.items()}

print(' After the switch: ')
print(Person)

The output result is:

[

Before the switch:
{'name': 'Tom', 'age': 22, 'city': 'Shanghai', 'ID': '073569'}
After the switch:
{'Tom': 'name', 22: 'age', 'Shanghai': 'city', '073569': 'ID'}

]

Ordered dictionary OrderedDict

The dictionary in Python is unordered, and the keys it pulls out are unordered because it is stored as hash. Sometimes, when we need the dictionary entries (items) or keys (keys) to be stored in order, we can use OrderedDict in the collections module, which is an ordered dictionary structure.

The sample code is as follows (Python version 3.5.2) :


from collections import OrderedDict

d = {}
d['Tom']='A'
d['Jack']='B'
d['Leo']='C'
d['Alex']='D'
print(' Unordered dictionary ( dict ) : ')
for k,v in d.items():
  print(k,v)

d1 = OrderedDict()
d1['Tom']='A'
d1['Jack']='B'
d1['Leo']='C'
d1['Alex']='D'
print('\n Ordered dictionary ( OrderedDict ) : ')
for k,v in d1.items():
  print(k,v)

The output result is:

[

Unordered Dictionary (dict) :
Leo C
Jack B
Tom A
Alex D

Ordered Dictionary (OrderedDict) :
Tom A
Jack B
Leo C
Alex D

]

Default dictionary ES118en. defaultdict

collections. defaultdict is a subclass of Python's built-in dict class. The first parameter provides an initial value for the default_factory attribute, which defaults to None. It overrides a method and adds a writable instance variable. Other features are the same as dict, but it avoids the KeyError exception by providing a default value for a key that does not exist.
We show the advantages of ES133en.defaultdict by taking the word frequency of the words in the list as an example.

1. In general, we count the word frequency code of the list as follows:


words = ['sun', 'moon', 'star', 'star',\
     'star', 'moon', 'sun', 'star']

freq_dict = {}
for word in words:
  if word not in freq_dict.keys():
    freq_dict[word] = 1
  else:
    freq_dict[word] += 1

for key, val in freq_dict.items():
  print(key, val)

The output results are as follows:

[

sun 2
moon 2
star 4

]

Using ES153en. defaultdict, the code can be optimized:


from collections import defaultdict

words = ['sun', 'moon', 'star', 'star',\
     'star', 'moon', 'sun', 'star']

freq_dict = defaultdict(int)
for word in words:
  freq_dict[word] += 1

for key, val in freq_dict.items():
  print(key, val)

Other default initial values can be set,list,dict, etc.

Access the values in the dictionary

Put the corresponding key in familiar square brackets as follows:


dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
# Output results of the above examples: 
#dict['Name']: Zara
#dict['Age']: 7

If you access the data with a key that is not in the dictionary, the output error is as follows:


dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Alice']: ", dict['Alice'];

Output results of the above examples:

[

#KeyError: 'Alice'[/code]

]

To modify a dictionary

New content is added to the dictionary by adding new key/value pairs, modifying or deleting existing key/value pairs as follows:


dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

 
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
# Output results of the above examples: 
#dict['Age']: 8
#dict['School']: DPS School

Delete dictionary elements

Elements that can delete list 1 can also clear the dictionary with just one operation.

Displays the del command for deleting 1 dictionary, as shown in the following example:


attrs = ['name', 'age', 'city', 'ID']
values = ['Tom', 22, 'Shanghai', '073569']
person = dict(zip(attrs, values))

print(person)

0

Dictionary built-in function & methods

The Python dictionary contains the following built-in functions:


attrs = ['name', 'age', 'city', 'ID']
values = ['Tom', 22, 'Shanghai', '073569']
person = dict(zip(attrs, values))

print(person)

1

The Python dictionary contains the following built-in methods:


attrs = ['name', 'age', 'city', 'ID']
values = ['Tom', 22, 'Shanghai', '073569']
person = dict(zip(attrs, values))

print(person)

2

Dictionary exercise code


print('''|--- Welcome to the address book program ---|
|---1 ,   Contact information query ---|
|---2 ,   Insert a new contact ---|
|---3 ,   Delete existing contacts ---|
|---4 ,   Exit the address book program ---|''')
addressBook={}# Definition address book 
while 1:
  temp=input(' Please enter the instruction code: ')
  if not temp.isdigit():
    print(" Incorrect instruction entered, please follow the prompt to enter ")
    continue
  item=int(temp)# Convert to numbers 
  if item==4:
    print("|--- Thanks for using the address book program ---|")
    break
  name = input(" Please enter the contact name :")
  if item==1:
    if name in addressBook:
      print(name,':',addressBook[name])
      continue
    else:
      print(" The contact does not exist! ")
  if item==2:
    if name in addressBook:
      print(" The name you entered already exists in the address book -->>",name,":",addressBook[name])
      isEdit=input(" Whether to modify contact information (Y/N ) :")
      if isEdit=='Y':
        userphone = input(" Please enter the contact number: ")
        addressBook[name]=userphone
        print(" Contact modified successfully ")
        continue
      else:
        continue
    else:
      userphone=input(" Please enter the contact number: ")
      addressBook[name]=userphone
      print(" Contact joined successfully! ")
      continue

  if item==3:
    if name in addressBook:
      del addressBook[name]
      print(" Delete successful! ")
      continue
    else:
      print(" The contact does not exist ")


Related articles: