Python101: 11. Dictionary

post thumb
Python
by Admin/ on 09 Jul 2021

Python101: 11. Dictionary

The dictionary in Python provides a flexible way to access and organize data

  • A dictionary is a collection of many values
  • The index of a dictionary can be of different data types, again not only integers, but also strings
  • The index of a dictionary is called a “key”, and the key and the value associated with the key are called a key-value pair (similar to a Map collection in Java)
  • Dictionaries are another mutable container model and can store objects of any type.
  • Each key-value key => value pair of the dictionary is separated by a colon : and each key-value pair is separated by a comma , and the whole dictionary is enclosed in parentheses {} in the following format.
dictionary = {'url1':'baidu', 'url':'google', 'num1':12, 'num2':34};

Keys are generally unique, and if a key is duplicated, the last key-value pair replaces the previous key-value pair, and there is no uniqueness requirement for the value, as follows.

dic1 = {'name':'zhangsan','age':23,'address':'BeiJing','name':'lisi'}

# Check the dictionary values to find duplicate keys and replace the previous ones with the later ones
dic1
# {'name': 'lisi', 'age': 23, 'address': 'BeiJing'}

dic1['name']
# 'lisi'

The value can take any data type, but the key must be immutable, such as a string, number or tuple, as follows.

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

1. Access to dictionary data


Create a dictionary and access the contents of the data dictionary. The following dictionary keys are ‘size’, ‘color’, ‘character’, and the values corresponding to these keys are ‘big’, ‘white’, and ‘gentle’. Accessing dictionary values can be done directly by adding keys inside square brackets, e.g.

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

# Dictionary values are accessed by ['key']
print(my_dog['size'])
# big # Output the result

print('My Dog has ' + my_dog['color']+' fur.' + ' and it has a ' + my_dog['character']+' character')
# My Dog has white fur. and it has a gentle character # output result

Similarly, dictionaries can use integers as keys, similar to the indexing of lists, except that the dictionary values can be of any integer type and need not start from 0, since the data type of the keys is arbitrary, as follows.

dic = {12:'big',0:'white',354:'gentle',1:'good'}

# Access the dictionary value with key 12
dic[12]
3 'big'

# Access the dictionary with key 0
dic[0]
3 'white'

Because dictionaries are not sorted, they cannot be sliced like lists. If you access a key that does not exist in the dictionary, you will get a KeyError error message. This is much like the “out-of-bounds” for lists IndexError error message.

Enter the following code in the interactive environment and note the error message displayed because for the absence of the ‘color’ key.

dic1 = {'name':'zhangsan','age':23,'address':'BeiJing'}

#Find the value in the dictionary with the key 'color'
dic1['color']
# Traceback (most recent call last):
#   File "<input>", line 1, in <module>
# KeyError: 'color'

2. Modify dictionary elements


2.1 Adding and updating dictionary data

Adding new content to the dictionary is done by adding new key/value pairs, modifying or deleting existing key/value pairs as shown in the following examples:

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

# Update
dic['Age'] = 8

# Add
dic['School'] = "Middle School"

# View dictionary data
dic
# {'Name': 'Fiona', 'Age': 8, 'Class': 'Three', 'School': 'Middle School'}

2.2 Deleting dictionary elements

Deletion of a dictionary element can be done either singly or by emptying the entire dictionary, as shown by deleting a dictionary using the del command "

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

# Delete the entry whose key is 'Name'
del dic['Name']

# Clear all entries of the dictionary
dic.clear()

# Delete the entire dictionary element
del dic

print ("dic['Age']: ", dic['Age'])
print ("dic['School']: ", dic['School'])

The above print statement raises an exception because the dictionary no longer exists after using del.

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

3. Characteristics of dictionary keys


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

Two important points to remember.

1) The same key is not allowed to appear twice. When creating if the same key is assigned twice, the latter value will be remembered, as in the following example:

Example

dic = {'Name': 'Fiona', 'Age': 10, 'Name': 'Manni'}

print("dic['Name']: ", dic['Name'])

# The output of the above example results in.
# dic['Name']: Manni

2) The key must be immutable, so it can be filled with a number, string or tuple, so it won’t work with a list, as in the following example:

dic = {['Name']: 'Fiona', 'Age': 10}
 
print("dic['Name']: ", dic['Name'])

# The output of the above example results in.
# Traceback (most recent call last):
#   File "test.py", line 3, in <module>
#     dic
#    = {['Name']: 'Zara', 'Age': 7}
# TypeError: list objects are unhashable

4. Functions of the dictionary


4.1 len()

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

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

4.2 str()

The str() method outputs the printable string identifiers in the dictionary

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

4.3 type()

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

dic = {'Name': 'Runoob', 'Age': 10, 'Class': 'Three'}

type(dic)
# <class 'dic'>

5. The dictionary approach


5.1 dic.clear()

Delete all elements of the dictionary, the clear() method does not return any value, the example is as follows.

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

print("dictionary length : %d" % len(dic))

dic.clear()
print("Length of dictionary after deletion : %d" % len(dic))

# The output results are.
# Dictionary length : 2
# Length after dictionary deletion : 0

5.2 dic.copy()

The copy() method makes a copy of the dictionary

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

dict11 = dic.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
dict1['user'] = 'root'
dict1['num'].remove(1)

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

Example dict2 is actually a reference to dict1, i.e., alias, so the output is consistent, dict3 deep copy of the parent object, the deep copy will not be modified with dict1, the child object is a shallow copy so modified with dict1, ** that is, the assignment will be modified with the parent object, the copy will not be modified with the parent object **, the above results The output is as follows.

{'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
The newly copied dictionary is : {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}

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

5.3 dic.fromkeys()

Create a new dictionary, using the elements of the sequence seq as keys of the dictionary, val is the initial value of all keys of the dictionary, the method returns a new dictionary

fromkeys() method syntax

dic.fromkeys(seq[, value])

# Parameters
seq -- The list of dictionary keys.
value -- Optional parameter, set the value corresponding to the key sequence (seq), default is None.

Example:

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

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

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

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

The result of the execution returns a new dictionary, if no value is specified the default is None, the output of the above result is

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

5.4 dic.get(key, default=None)

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

get() method syntax

dic.get(key, default=None)

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

Example:

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

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

The above result is output as:

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

5.5 key in dic

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

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

# Check if the key Age exists
if 'Age' in dic:
    print("Key Age exists")
else:
    print("Key Age does not exist")

# Check if the key Sex exists
if 'Sex' in dic:
    print("Key Sex exists")
else:
    print("Key Sex does not exist")

# not in

# Check if the key Name exists
if 'Name' is not in dic:
    print("Key Name does not exist")
else:
    print("Key Name exists")

The above result is output as:

Key Age exists
Key Sex does not exist
Key Name exists

5.6 dic.items()

The item() method returns an array of traversable (key, value) tuples as a list

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

print ("Value : %s" % dic.items())

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

Examples of traversable tuple arrays:

dict1 = {'oldest':'25 years old',
        'second':'20 years old',
        'third':'12',
        }

print(dict1.items())

for key,values in dict1.items():
    print(key + 'already' + values + 'up')

The above result is output as:

The oldest is 25 years old
The second is 20 years old
The third is 12 years old

Process finished with exit code 0

5.7 dic.keys()

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

keys() method syntax:

dic.keys()

Example:

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

print(dic.keys())

The above result is output as:

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

From the result, we see that the result returns an iterative object, which we can then convert to a list using the list.

list1 = list(dic.keys())
print ("The result of the conversion is : %s" % list1)

# The output is a list, which can be subsequently manipulated accordingly.
# The result after conversion is : ['Name', 'Age']

5.8 dic.setdefault(key, default=None)

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

setdefault() method syntax:

dic.setdefault(key, default=None)
# Parameters
key -- The key value to look up.
default -- The default key value to set if the key does not exist.

Example:

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

print ("Age key value is : %s" % dic.setdefault('Age', None))
print ("The value of the Sex key is : %s" % dic.setdefault('Sex', None))
print ("The new dictionary is:", dic)

The above result is output as:

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

5.9 dic.update(dict2)

The Python dictionary update() function updates the key/value pairs of the dictionary argument dict2 to the dictionary dic.

Syntax:

dic.update(dict2)
# Parameters
 dict2 -- The dictionary to add to the specified dictionary dic
.

Example:

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

# Add the result from dict2 to the dictionary dic
dic.update(dict2)
print("Update dictionary dic : ", dic)

The above result is output as:

Update dictionary dic : {'Name': 'Mary', 'Age': 17, 'Sex': 'female'}

5.10 dic.values()

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

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

print("All values of dictionary are : ", list(dic.values()))

The output of the above result is:

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

5.11 dic.pop(key[,default])

The Python dictionary pop() method deletes the value corresponding to a given key key of the dictionary, returning the value that was deleted. key value must be given. Otherwise, the default value is returned.

pop() method syntax:

pop(key[,default])
#Parameters
key: the key value to be deleted
default: If there is no key, return the default value

# Return Value
Returns the value that was deleted.

Example:

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

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

print(result)

The above result is output as:

17

Process finished with exit code 0

5.12 dic.popitem()

The Python dictionary popitem() method returns a random key-value pair (key,value) in the form of a LIFO (Last In First Out) order, i.e., the last key-value pair. If the dictionary is empty and this method is called, a KeyError exception is thrown.

Example:

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

The above result is output as:

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

Empty the dictionary of.

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

print(dic.popitem())

The result output is:

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

6. Dictionaries and lists


6.1 Dictionary and list differences

The elements of a list are ordered because the elements are stored incrementally from 0 through the sequence, while the contents of a dictionary are not ordered, as the following example illustrates well.

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 example, we can see that when the contents of the list elements are the same, the order is different and then compare the contents when the matching is not successful, the same way the dictionary values match successfully, indicating that the contents of the elements in the dictionary are not stored in order.

Summary


This section gives an introduction to the operation and use of Python data structures with dictionaries, and provides support for some of the basics of using dictionaries for Python engineers.


Reference

http://www.pythondoc.com/pythontutorial3 https://www.runoob.com/python3/python3-dictionary.html https://github.com/JustDoPython/python-100-day/tree/master/day-011

comments powered by Disqus