Python dictionary usage

Keywords: Python

Python dictionary usage

There is also a data structure in python that is particularly important, that is, a dictionary. The dictionary is composed of key value one-to-one correspondence. Such key value combinations are called terms. Key and value are separated by ':', and items are separated by ','.
The dictionary is represented by curly brackets' {} '. To make a difference, the list is represented by '[]', and the tuple is represented by '()'.
First, let's see how to create a dictionary.

#Here is an example of phonebook
phonebook = {'A': '1234567', 'B': '223344556', 'C': '334455667'}
A = phonebook['A']
print(A)

#The dictionary can also be created by using the function dict
items = [('name', 'Lisa'), ['age', 23]]
d = dict(items)
print(d['name'])
print(d['age'])
#Of course, it can be simplified as follows
d = dict(name='lisa', age=23)
print(d['name'])
print(d['age'])

The operation results are shown as follows:

The following describes the basic operation of the dictionary (5 types):
The basic operation of a dictionary is a bit similar to that of a sequence.

#On the basic operation of dictionaries
phonebook = {'A': '1234567', 'B': '223344556', 'C': '334455667'}
#1. Length len number of returned items len (obj)
print(len(phonebook))

#2. Return the value obj[key] corresponding to the key
B = phonebook['B']
print(B)

#3. Key value association this method can change the value corresponding to its key
C = '22'
phonebook['C'] = C
print(phonebook['C'])

#4. Delete del obj[key] delete key
del phonebook['C']
print(phonebook)

#5. Search key in obj for membership
if 'A' in phonebook:
    print("phonebook has 'A'")

The operation results are as shown in the figure

Of course, dictionaries have many other ways. Here is an overview:
1.clear method
Empty the dictionary directly and return an empty dictionary.

phonebook = {'A': '1234567', 'B': '223344556', 'C': '334455667'}
print('The original dictionary is:', phonebook)
phonebook.clear()
print('clear After that:', phonebook)

The operation results are shown as follows:

2.copy method
Obviously, this is just a copy of the dictionary. But it should be noted that the copy here is only a shallow copy.

phonebook = {'A': '1234567', 'B': '223344556', 'C': '334455667'}

phonebook2 = phonebook.copy()

print('copy After that, phonebook2 Is:', phonebook2)

#Notice, this copy is just a shallow copy

The operation results are shown as follows:

3.fromkeys method
The fromkeys method can create a new dictionary and only new keys, but the default value is None.
Of course, you can also customize the corresponding value of the key. Similarly, the default value is set.

#Create a new dictionary with the fromkeys method. The default value of the dictionary is None, but you can define it yourself
A = dict.fromkeys(['name', 'age'])
print(A)

B = dict.fromkeys(['name', 'age'], '(unknown)')
print(B)

The operation results are shown as follows:

4.setdefault method
The setdefault method is similar to the fromkeys method. It is equivalent to setting the default value. However, this method is more suitable for setting default values.

#The setdafult method adds the specified key value correspondence to the dictionary, but the value is the default value, which can be changed and replaced. It's a bit like the get method.
#Let's create a new empty dictionary first
T = {}
T.setdefault('num', '(unknown)')
print(T)
#The value of num is changed here.
T['num'] = '12333'
T.setdefault('num', '(unknown)')
print(T)

The operation results are shown as follows:

5.get method
get method is an extension of dictionary access, providing a more relaxed environment.
If the key is accessed directly, the program will report an error if the key does not exist.

#If you directly access a key that does not exist in the dictionary, an error will be reported
phonebook = {'A': '1234567', 'B': '223344556', 'C': '334455667'}
print(phonebook['D'])


However, if you use the get method to search, even if the key does not exist, it will not report an error. Only one value of None will be returned.

phonebook = {'A': '1234567', 'B': '223344556', 'C': '334455667'}

#But using the get method only returns None
T = phonebook.get('D')
print(T)
#The same get method is the same as ordinary search
print(phonebook.get('A'))

The operation results are shown as follows:

6.keys method
The keys method is to integrate all the keys in the dictionary into a list and return them.

#The keys method returns all keys in the dictionary in the form of a list
phonebook = {'A': '1234567', 'B': '223344556', 'C': '334455667'}
print(phonebook.keys())

The operation results are shown as follows:

7.values method
The values method, which consolidates all the values in the dictionary into a list and returns them.

#Method values is relative to method key, and returns the dictionary value in the form of a list
phonebook = {'A': '1234567', 'B': '223344556', 'C': '334455667'}
print(phonebook.values())

The operation results are shown as follows:

8.items method
The items method, which consolidates all items in the dictionary into a list and returns them.

#Method items returns the list containing all dictionary items in the list
phonebook = {'A': '1234567', 'B': '223344556', 'C': '334455667'}
print(phonebook.items())

The operation results are shown as follows:

The three methods here, keys, values, and items, respectively correspond to the key, value, and item in the dictionary. They are all to integrate and return the corresponding contents in the dictionary in the form of a list.
9.pop method
pop method, delete the item corresponding to the key, and return the value corresponding to the key. If the key is not specified, the last key will be deleted.

#The pop method deletes the item corresponding to the key and returns the value corresponding to the key
phonebook = {'A': '1234567', 'B': '223344556', 'C': '334455667'}
print('customary phonebook Is:', phonebook)
#Delete the item with key 'A' and return the corresponding value of the key
T = phonebook.pop('A')
print(T)
print('current phonebook Is:', phonebook)

The operation results are shown as follows:

10.popitem method
The popitem method removes the last entry from the dictionary.
Some books write random pop-up, but in practice, pop-up is always the last item.

#popitem method, just like the name, pops up the last item. But some books say that random pop-up is the last one after practice.
phonebook = {'A': '1234567', 'B': '223344556', 'C': '334455667', 'D': '28288288', 'E': '37377737'}
T = phonebook.popitem()
print(T)

The operation results are shown as follows:

11.update method
The update method is an update method for the dictionary content.
You can add new items or replace existing ones.

#Method update uses the values contained in the dictionary to update the data, or you can directly add new items to the dictionary.
T = {
    'A': 'Lisa',
    'B': 'Six',
    'C': 'DD'
}

P = {
    'D': 'test',#New item
    'A': 'Peter'#Existing key 'A' for data change
}

T.update(P)

print(T)

The operation results are shown as follows:

I hope I can help you. Thank you~

Posted by amitdubey2 on Wed, 10 Jun 2020 21:07:23 -0700