Hello, I am Ma Nongfei ge, thank you for reading this article, welcome one button three lian oh. This article focuses on dict dictionaries of Python data types, which we’ll cover in one go. Dry goods full, suggested collection, need to use often look. If you have any questions or need, you are welcome to send me a message.

What is a dictionary?

We introduced it in the last articlePython’s built-in data types — lists and tuples — are available in 10 chaptersLists and tuples are two very common sequences. Today, we’ll cover another widely used sequence called dict. Even if you don’t know the dict data type, you’ve probably heard the name —->Xinhua dictionaryCan’t nobody use it!!See this picture, does not recall childhood school memories. Remember how we looked up a Chinese character in Xinhua Dictionary? Is it based onPinyin to find Chinese characters, the specific details of the search I believe we all understand. In the same way that dictionaries in Python find values by keys, dict’s underlying data structures are hash tables.

How do I use a dictionary?

Having said the basic concepts of dictionaries, it is time to talk about how dictionaries are used. Only things that work are good. This chapter will introduce the addition, deletion, modification and checking of dictionaries. The basic structure of a dictionary is:

{'key1':'value1'.'key2':'value2'. .'keyn':valuen}
Copy the code

Among themkey1~keynSaid key,value1~valuenRepresents the value of the key.Note that all keys in the dictionary are unique (each person is unique), there is only one key that can be null, None, and only immutable types such as strings, integers, decimals, and tuples. The value can be any Python supported data type and the value can be the null value None. There is no limit to the number of values that can be the null value None.

Create a dictionary

There are many ways to create a dictionary. Here are some of the most common ways. Dictname ={‘key1′:’value1’, ‘key2′:’value2’,… , ‘keyn’:valuen} Dictname = dict.fromkeys(list,value =None), where the list parameter represents the list of all keys in the dictionary, and the value parameter represents the default value. If not written, all values are null. The third: using the dict method, which falls into four cases:

  1. Dict () -> Creates an empty dictionary
  2. Dict (mapping) -> Creates a dictionary initialized with keys from the mapping key and value.
  3. Dict (iterable) -> Creates a dictionary that iterable is iterated over to get its keys when initialized.
for k, v in iterable:
                d[k] = v
Copy the code
  1. dict(**kwargs) -> **kwargsIs a mutable function called in the syntactic format:dict(key1=value1,key2=value2,... keyn=valuen), such as:Dict (name=' NNFLG ', age=17, weight=63)

These three ways to create a dictionary are covered, so let’s take a look at some examples:

#1. Create a dictionary
d = {'name': 'Code Nongfei'.'age': 18.'height': 185}
print(d)
list = ['name'.'age'.'height']
# 2. Fromkeys method
dict_demo = dict.fromkeys(list)
dict_demo1 = dict.fromkeys(list.'test')
print(dict_demo)
print(dict_demo1)
Create a dictionary via dict() mapping, passing in lists or tuples
demo = [('name'.'Code Nongfei'), ('age'.19)]
dict_demo2 = dict(demo)
print(dict_demo2)
dict_demo21 = dict(name='Code Nongfei', age=17, weight=63)
print(dict_demo21)

Copy the code

The results are as follows:

{'name': 'Code Nongfei'.'age': 18.'height': 185}
{'name': None.'age': None.'height': None}
{'name': 'test'.'age': 'test'.'height': 'test'}
{'name': 'Code Nongfei'.'age': 19}
{'name': 'Code Nongfei'.'age': 17.'weight': 63}
Copy the code

Dictionary access

Having said that, let’s look at dictionary access. Dictionaries differ from lists and tuples in that their elements are not sequentially stored in memory areas; Therefore, elements in a dictionary cannot be accessed by index, only by key. It can be written in two different ways.

  1. The syntax format for the first way isdictname[key], dictname indicates the name of the dictionary and key indicates the specified key. If the specified key does not exist,A KeyError is reported.
  2. The syntax of the second way isdictname.get(key), dictname indicates the name of the dictionary and key indicates the specified key. None is returned if the specified key does not exist.

For example, the following code means to find the value of the key based on its name.

dict_demo5 = {'name': 'Code Nongfei'.'age': 18.'height': 185}
print(dict_demo5['name'])
print(dict_demo5.get('name'))
print('Key not present returns result =',dict_demo5.get('test'))
Copy the code

The results are as follows:

If the nonexistent key is returned = NoneCopy the code

Add and modify key-value pairs

Dictname [key]=value; if the key does not exist in the dictionary, a new key/value pair is added. If the key exists in the dictionary, the value corresponding to the original key is updated. Sex =’ male ‘sex=’ male’ sex=’ male ‘

# add key-value pairs
dict_demo6 = {'name': 'Code Nongfei'.'age': 18.'height': 185}
dict_demo6['sex'] = 'male'
print('Result of new key-value pairs ={0}'.format(dict_demo6))
# change key-value pairs
dict_demo6['height'] = 190
print('Result of modifying key-value pairs ={0}'.format(dict_demo6))
Copy the code

The results are as follows:

The result of the new key/value pair = {' age: 18, 'name' : 'yards farmers flying elder brother', 'height: 185,' sex ':' male '} to modify the result of key/value pair = {' age: 18, 'name' : 'yards farmers flying elder brother', 'height' : 190, 'sex': 'male '}Copy the code

Of course, modification and deletion of key-value pairs can also be achieved through the update method, whose specific syntax format is dictname.update(dict), where dictname is the name of the dictionary and dict is the value of the dictionary to be modified. This method can either add or modify key-value pairs. This method returns no value, that is, it modifies the element on the original dictionary. In this example, the key name is set to 1024 and age is set to 25. And a new key-value pair like= learning.

# update dict_demo7 = {'name': 'width': 100} dict_demo7. Update ({'name': 'width': 100) 'feifei 1024', 'age: 25,' like ', 'learning'}) print (' update method returns the = {}, dict_demo7)Copy the code

The running results are as follows:

Update method returns the = {} {' height: 185, 'like', 'learning', 'width: 100,' name ':' feifei 1024 ', 'age: 25}Copy the code

Delete key-value pairs

There are three ways to delete key-value pairs:

  1. The first is adel dictname[key], del keyword is used, where dictname is the dictionary name and key is the key to be deleted. A KeyError is reported if the key does not exist.
  2. The second way is through the POP method, which has a syntactic structure:dictname.pop(key). This method is used to delete the specified key-value pair. No value is returned. No error is reported if the key does not exist.
  3. The third way is through the popItem method, which has this syntax:dictname.popitem(). This method is used to delete the last key-value pair in the dictionary. Here are some examples:
dict_demo10 = {'name': 'Code Nongfei'.'age': 18.'height': 185.'width': 100}
Delete key-value pairs
del dict_demo6['height']
print('Delete height =', dict_demo6)
# pop() and popItem () methods
dict_demo10.pop('width')
print('pop method call to remove key width result =', dict_demo10)
dict_demo10 = {'name': 'Code Nongfei'.'age': 18.'height': 185.'width': 100}
dict_demo10.popitem()
print('popitem方法调用之后结果=', dict_demo10)
Copy the code

The results are as follows:

{'name': 'height', 'sex': 'male ', 'age': 18} pop = {'name': 'height', 'age': 185, 'age': 18} 18} popitem = {'width': 100, 'name': 'nongfei ', 'height': 185}Copy the code

You can see that the popItem method removes not the last key width, but the key age. And the order of the elements in the dictionary changes.

Other methods:

  1. If the specified key exists in the dictionary, the syntax is:key in dictname, where the dictname is the dictionary name. In indicates whether the search key exists in the dictionarynot inThe keyword. Here’s an example:
dict_demo6 = {'name': 'Code Nongfei'.'age': 18.'height': 185}
print('The result for the key name is =', ('name' in dict_demo6))
Copy the code
  1. To print out all the keys in the dictionary, the method called iskeys(), its grammatical structure is:dictname.keys(). Dictname is the dictionary name.
  2. To print all the values in the dictionary, the method called isvalues(), its grammatical structure is:dictname.values().
  3. To print all the key-value pairs in the dictionary, the method is calleditems(), its grammatical structure is:dictname.items().

Here’s an example:

dict_demo7 = {'name': 'Code Nongfei'.'age': 18.'height': 185.'width': 100}
print('keys' returns result =', dict_demo7.keys())
print(The 'value method returns the result =', dict_demo7.values())
print('item method returns result =', dict_demo7.items())
Copy the code

The output is:

Keys = dict_keys(['width', 'name', 'height', 'age']) value = dict_values([100, 'nonferg ', 185, 18]) item () method returns results = dict_items ([(' width ', 100), (' name ', 'code farmer flying elder brother), (' height, 185), (" age ", 18)])Copy the code

Use dictionaries to format strings

In the sequence article, we introduced that specifiers can be converted sequentially. The syntax format is {num}, where num is a number, incremented from 0, and the format method is used to format a string. The downside of this approach, however, is that it can be difficult to use when there are a lot of conversion specifiers in the string.

str = 'Code Nongfego {0}, you must have ={1}'
print(str.format('come on'.'promise'))
Copy the code

The output result is code nongfeige refueling, you will have = outstanding, here to pass the parameters in strict accordance with the order. The syntax is %(name)s, where % is a fixed notation, name corresponds to the key in the dictionary, s represents the type of the dictionary value whose key is name, or s if it is a string. At last, the formatted string should be output by STR % dictName, where STR is the original string and dictName is the dictionary name. Give me an example!

str = 'S =%(num)s =%(article)s, hope =%(reader)s'
dict_demo12 = {'num': 250.'article': 'articles'.'reader': 'Readers'}
print(str % dict_demo12)
Copy the code

The run result isCode nongfei brother's first =250 = article, hope = readers like it

conclusion

This article introduces the basic concepts and usage of the Python dictionary in detail.


Good article recommendation

Python’s built-in data types — lists and tuples — are the most common types of data in Python. What are the built-in data types in Python? Just to get a sense of the numbers

I am Mynongfei and thank you again for reading this article. Welcome to pay attention to my public number [code nongfei brother]. Enjoy the joy of sharing