Pthon Beginner 6: Pthon Dictionary Details

Keywords: Python Java Google

Dictionaries in Python provide a flexible way to access and organize data

  • A dictionary is a collection of values
  • Dictionary indexes can be of different data types, not just integers, but also strings
  • Dictionary indexes are called keys, and the values associated with keys are called key-value pairs (similar to Map collections in Java)
  • Dictionaries are another variable container model and can store any type of object.
  • Each key value key=>value pair of the dictionary is colon: split, comma between each key value pair, split, and the entire dictionary is enclosed in curly braces {} in the following format:
dictionary  = {'url1':'baidu', 'url':'google', 'num1':12, 'num2':34};

Keys are generally unique. If keys are repeated, the last key-value pair replaces the previous one. Values do not have a uniqueness requirement, as follows:

dic1 = {'name':'zhangsan','age':23,'address':'BeiJing','name':'lisi'}
# Looking at Dictionary values found duplicate key values followed by replacements preceding
dic1
{'name': 'lisi', 'age': 23, 'address': 'BeiJing'}

dic1['name']
'lisi'

Values can be of any data type, but keys must be immutable, such as strings, numbers, or tuples, as follows:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258',('a','b'):(12,43)}

1. Access dictionary data

Create a dictionary and access the contents of the data dictionary. The keys of the following dictionary are'size','color','character', and their corresponding values are'big','white','gentle'. Accessing the values of the dictionary can be accessed directly by adding keys in square brackets, for example:

MyDog = {'size':'big','color':'white','character':'gentle'}

# Dictionary values are accessed by ['key']
print(MyDog['size'])
 big   #Output Results

print('My Dog has '+MyDog['color']+' fur.' + ' and it has a ' + MyDog['character']+' character')
My Dog has white fur. and it has a gentle character #Output Results

Similarly, a dictionary can use integers as keys, similar to the index of a list, except that the value of the dictionary is of any integer type and does not have to start at 0 because the data type of the key value is arbitrary, as follows:

MyCon = {12:'big',0:'white',354:'gentle',1:'good'}
# Dictionary value with access key 12
MyCon[12]
'big'
# Dictionary value with access key 0
MyCon[0]
'white'

Because dictionaries are not sorted, they cannot be sliced like lists.
Accessing keys that do not exist in the dictionary will cause KeyError to error information.It's much like the list's "out of bounds"
IndexError error message.Enter the following code in an interactive environment and note the error message displayed because
For no'color'key:

dic1 = {'name':'zhangsan','age':23,'address':'BeiJing'}
#Find a value with a key of'color'in the dictionary
dic1['color']
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'color'

2. Modify dictionary elements

2.1 Add and update dictionary data

The way to add new content to a dictionary is to add new key/value pairs and modify or delete existing key/value pairs as follows:

dict = {'Name': 'Fiona', 'Age': 10, 'Class': 'Three'}
# To update
dict['Age'] = 8 
# Add to
dict['School'] = "Middle School" 
# View Dictionary Data 
dict
{'Name': 'Fiona', 'Age': 8, 'Class': 'Three', 'School': 'Middle School'}

2.2 Delete dictionary elements

Deleting a dictionary element can either delete it alone or empty the entire dictionary. Deleting a dictionary displayed uses the del command.

dict = {'Name': 'Fiona', 'Age': 10, 'Class': 'Three'}

# Delete key is an entry of'Name' 
del dict['Name']  

# Empty all entries in the dictionary
dict.clear()  

# Delete entire dictionary element
del dict          
 
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

This raises an exception because the dictionary after del no longer exists:

Traceback (most recent call last):
  File "test.py", line 12, in <module>
    print("dict['Age']: ", dict['Age'])
TypeError: 'type' object is not subscriptable

3. Characteristics of dictionary keys

Dictionary values can take any python object without restrictions, either standard or user-defined, but keys do not work.

Two important points to remember:

1) The same key is not allowed to appear twice.If the same key is assigned twice at creation time, the latter value will be remembered, as in the following example:

Example

dict = {'Name': 'Fiona', 'Age': 10, 'Name': 'Manni'} 
 
print "dict['Name']: ", dict['Name']

# The above example outputs the results:

dict['Name']:  Manni

2) Keys must be immutable, so they can be used as numbers, strings, or tuples, so lists are not possible, as in the following example:

dict = {['Name']: 'Fiona', 'Age': 10} 
 
print "dict['Name']: ", dict['Name']

# The above example outputs the results:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'Zara', 'Age': 7} 
TypeError: list objects are unhashable

4. Dictionary functions

4.1 len()

The len() method calculates the number of dictionary elements (the total number of keys)

>>> dict = {'Name': 'Fiona', 'Age': 10, 'class': 'Three'} 
 >>> len(dict)
     3

4.2 str()

Printable string identifiers in the str() method output dictionary

>>> dict = {'Name': 'Runoob', 'Age': 10, 'Class': 'Three'}
>>> str(dict)
"{'Name': 'Runoob', 'Age': 10, 'Class': 'Three'}"

4.3 type()

The type() method returns the type of variable entered, or the dictionary type if the variable is a dictionary.

>>> dict = {'Name': 'Runoob', 'Age': 10, 'Class': 'Three'}
>>> type(dict)
<class 'dict'>

5. Method of Dictionary

5.1 dict.clear()

Delete all elements in the dictionary, and the clear() method does not have any return values, as shown in the following example:

dict = {'Name': 'Fiona', 'Age': 10}

print ("Dictionary length:%d"%len(dict)))
dict.clear()
print ("Dictionary deleted length:%d"%len(dict)))

#The output is:
Dictionary length: 2
 Length after dictionary deletion: 0

5.2 dict.copy()

copy() method copies dictionary

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

dict11 = dict.copy()
print(dict11)
print("The newly copied dictionary is : ", dict11)

dict1 = {'user': 'runoob', 'num': [1, 2, 3]}

# Shallow copy: reference object assignment
dict2 = dict1  
# Copy
dict3 = dict1.copy()  

# Modify data data data
dict1['user'] = 'root'
dict1['num'].remove(1)

# Output Results
print(dict1)
print(dict2)
print(dict3)

dict2 in the instance is actually a reference to dict1, which is an alias, so the output results are consistent. dict3 makes a deep copy of the parent object, the deep copy will not be modified with dict1 modification, the child object is a shallow copy so the assignment will be modified with the modification of the parent object, and the copy will not be modified with the modification of the parent object. The output of the above results is as follows:

{'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
The newly copied dictionaries are: {'Name':'Runoob','Age': 7,'Class':'First'}

{'user': 'root', 'num': [2, 3]}
{'user': 'root', 'num': [2, 3]}
{'user': 'runoob', 'num': [2, 3]}

5.3 dict.fromkeys()

Create a new dictionary that uses the elements in the sequence seq as keys to the dictionary, and val as initial values for all keys in the dictionary. This method returns a new dictionary

fromkeys() method syntax

dict.fromkeys(seq[, value])

# parameter
seq -- A list of dictionary key values.
value -- Optional parameters, Set the key sequence ( seq)Corresponding value, default is None. 

Example:

# dict.fromkeys(seq[, value])
seq = ('name', 'age', 'class')

# No value specified
dict = dict.fromkeys(seq)
print("The new dictionary is : %s" % str(dict))

# Assignment 10
dict = dict.fromkeys(seq, 10)
print("The new dictionary is : %s" % str(dict))

#Assign a tuple
dict = dict.fromkeys(seq,('zs',8,'Two'))
print("The new dictionary is : %s" % str(dict))

The result of execution returns a new dictionary. If you do not specify a value that defaults to None, the output of the above result is:

The new dictionary is: {'name': None,'age': None,'class': None}
The new dictionary is: {'name': 10,'age': 10,'class': 10}
The new dictionaries are: {'name': ('zs', 8,'Two'),'age': ('zs', 8,'Two'),'class': ('zs', 8,'Two')}

5.4 dict.get(key, default=None)

Returns the value of the specified key, or default if the value is not in the dictionary

get() method syntax

dict.get(key, default=None)

# parameter
key -- The key to look for in the dictionary.
default -- Returns the default value if the value of the specified key does not exist.

Example:

# Example application of get () method
dict = {'Name': 'Mary', 'Age': 20}

print ("Age Value is : %s" %  dict.get('Age'))
print ("Name Value is : %s" %  dict.get('Name'))
print ("Sex Value is : %s" %  dict.get('Sex', "NA"))

The output of the above results is:

Age value: 20
 Name value: Mary
 The Sex value is: NA

5.5 key in dict

Returns true if the key is in dictionary dict, false otherwise

dict = {'Name': 'Mary', 'Age': 20,'Address':'BeiJing'}

# Detect whether the key Age exists
if 'Age' in dict:
    print("key Age existence")
else:
    print("key Age Non-existent")

# Detect the existence of key Sex
if 'Sex' in dict:
    print("key Sex existence")
else:
    print("key Sex Non-existent")

# not in

# Detect whether the key Name exists
if 'Name' not in dict:
    print("key Name Non-existent")
else:
    print("key Name existence")

The output of the above results is:

Key Age Exists
 Key Sex does not exist
 Key Name Exists

5.6 dict.items()

The item() method returns a traversable (key, value) tuple array as a list

dict = {'Name': 'Mary', 'Age': 17}
 
print ("Value : %s" %  dict.items())

# The output is:
Value : dict_items([('Age', 17), ('Name', 'Mary')])

Examples of traversable tuple arrays:

dict1 = {'Boss':'25 year',
        'penis':'20 year',
        'Third':'12 year',
        }
print(dict1.items())
for key,values in dict1.items():
    print(key + 'Already' + values + 'Yes')

The output of the above results is:

The elder is 25 years old
 The sophomore is already 20 years old
 The third person is 12 years old

Process finished with exit code 0

5.7 dict...keys()

Returns an iterator that can be converted to a list using list()

keys() method syntax:

dict.keys()

Example:

dict = {'Name': 'Mary', 'Age': 17}

print(dict.keys())

The output of the above results is:

dict_keys(['Name', 'Age'])

The result shows that the result returns an iteration object, so we can use list to convert to list:

list1 = list(dict.keys())
print ("converted result:%s"%list1)

#Output results are a list that can be manipulated later:
The result of the conversion is: ['Name','Age']

5.8 dict...setdefault(key, default=None)

The Python dictionary setdefault() method is similar to the get() method in that it returns the corresponding value if the key is in the dictionary.If it is not in the dictionary, insert the key and the default value set, and return default, which is None.

setdefault() method syntax:

dict.setdefault(key, default=None)
# parameter
key -- The key value to find.
default -- The default key value set when the key does not exist.

Example:

dict = {'Name': 'Mary', 'Age': 17}
 
print ("Age The value of the key is : %s" %  dict.setdefault('Age', None))
print ("Sex The value of the key is : %s" %  dict.setdefault('Sex', None))
print ("The new dictionary is:", dict)

The output of the above results is:

The Age key has a value of: 17
 The value of the Sex key is: None
 The new dictionary is: {'Age': 17,'Name':'Mary','Sex': None}

5.9 dict...update(dict2)

The Python dictionary update() function updates the key/value (key/value) pair of dictionary parameter dict2 to the dictionary dict.

Grammar:

dict.update(dict2)
# parameter
 dict2 -- Add to specified dictionarydictA dictionary in.

Example:

dict = {'Name': 'Mary', 'Age': 17}
dict2 = {'Sex': 'female' }

# Add results from dict2 to dictionary Dict
dict.update(dict2)
print ("Update Dictionary dict : ", dict)

The output of the above results is:

Update Dictionary dict: {'Name':'Mary','Age': 17,'Sex':'female'}

5.10 dict.values()

The Python dictionary values() method returns an iterator that can be converted to a list using list(), which is all the values in the dictionary.

dict = { 'Name': 'Mary','Sex': 'male', 'Age': 7}

print("All values in the dictionary are : ", list(dict.values()))

The output of the above results is:

All values in the dictionary are: ['Mary','male', 7]

5.11 dict.pop(key[,default])

The Python dictionary pop() method deletes the value corresponding to the given key in the dictionary and returns the deleted value.The key value must be given.Otherwise, return the default value.
pop() method syntax:

pop(key[,default])
#Parameters
 Key:The key value to delete
 Default: Returns a default value if there is no key

#Return value
 Returns the deleted value.

Example:

dict = {'Name': 'Mary', 'Age': 17}

result = dict.pop('Age') # delete

print(result)

The output of the above results is:

17

Process finished with exit code 0

5.12 dict.popitem()

The Python dictionary popitem() method randomly returns a key-value pair in the form of a LIFO (Last In First Out LIFO) sequence rule, which is the last key-value pair.
If the dictionary is already empty and this method is called, a KeyError exception is reported.

Example:

dict = {'Name': 'Mary', 'Age': 17}
pop_obj=dict.popitem()
print(pop_obj)
print(dict)

The output of the above results is:

('Age', 17)
{'Name': 'Mary'}

Empty the dictionary:

dict = {'Name': 'Mary', 'Age': 17}
del dict

print(dict.popitem())

The output is:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print(dict.popitem())
TypeError: descriptor 'popitem' of 'dict' object needs an argument

6. Dictionaries and Lists

6.1 Dictionary and List Differences

The table items of the elements in the list are sorted because the elements are stored incrementally from 0 through the sequence. The table items of the dictionary contents are not sorted. The following examples illustrate the difference between a list and a dictionary:

list1 = ['zhangsan',23,'BeiJing']
list2 = ['BeiJing','zhangsan',23]
list1 == list2
False
dic1 = {'name':'zhangsan','age':23,'address':'BeiJing'}
dic2 = { 'age':23,'name':'zhangsan','address':'BeiJing'}
dic1 == dic2
True

From the above examples, it can be seen that the matching is unsuccessful when the contents of the list elements are identical, the order is different, and the matching of the same dictionary values is successful, indicating that the elements in the dictionary are not stored in the order.

summary

This section summarizes the python data structure dictionary and paves the way for the future use of related knowledge.

Published 30 original articles, won 31 reviews, and visited 3055
Private letter follow

Posted by susi on Sun, 12 Jan 2020 19:23:33 -0800