Python Foundation - Data Types - Dictionaries

Keywords: Python

Python Foundation - Data Types - Dictionaries

** {key:value} ** A set of unordered key-value pairs with mapped relationships
Indexing is not possible because it is out of order
key is immutable, value can take any data type
The key must be unique, but the value does not.

Create Dictionary

  • Method 1: Create directly
#Create a dictionary directly
roman_dict = {'1':'I',2:'II','3':'III','4':'IV'}#Create a dictionary directly
  • Method 2: Call dict() function to create
    Form 1: List Set Tuples
lis =[('1','I'),('2','II'),('3','III'),('4','IV')]#Form 1: List Set Tuples
nome_dict = dict(lis)#Call dict() function to create
print(nome_dict)

Output:

Form two: tuple set tuple

tup = ((1,'kiki'),(2,'Jack'),(3,'Tom'),(4,'Rouse'))#Form two: tuple set tuple
nome2_dict = dict(tup)#Call dict() function to create
print(nome2_dict)

Output:

Dictionary Stitching

Dictionary does not support'+'operation

  • Method One
    Dictionary stitching should be done using
dict.update(dict2)

With the add function dict.update(), note that dictionary elements with the same key are replaced when added
Example:

#Define two dictionaries:
roman_dict = {'1':'I',2:'II','3':'III','4':'IV'}
tup = ((1,'kiki'),(2,'Jack'),(3,'Tom'),(4,'Rouse'))#Form two: tuple set tuple
nome2_dict = dict(tup)
roman_dict.update(nome2_dict)#Perform splicing of dictionaries
print('Two dictionaries were added and stitched:\n',roman_dict)

Output:

  • Method 2
    Dictionaries are converted to tuple collections using dict.items(), and then to dictionaries or tuples using list() or tuple() functions
    Then add the tuple sets that make up the rows, and convert dict() to a dictionary
#Define two dictionaries:
roman_dict = {'1':'I',2:'II','3':'III','4':'IV'}
nome2_dict = {1: 'kiki', 2: 'Jack', 3: 'Tom', 4: 'Rouse'}
#Converts a dictionary into a list set tuple using dict.items(), and then into a dictionary
lis1 = list(dict.items(roman_dict))
lis2 = list(dict.items(nome2_dict))
#List Additive Stitching
lis = lis1+lis2
dic = dict(lis)#Convert to Dictionary
print(dic)

Output:

Dictionary Access

Both methods pass in key, but the difference is:

Retrieve by key value

The program crashes when the key does not exist.

roman_dict = {'1':'I',2:'II','3':'III','4':'IV'}
print(roman_dict['1'])#Method one, dict[key], program crashes when key does not exist
print(roman_dict[2])

Output:

Retrieve by dict.get()

When the key does not exist, the program returns None and does not crash.

roman_dict = {'1':'I',2:'II','3':'III','4':'IV'}
print(roman_dict.get('2'))#dict.get(key), returns None when the key does not exist, and the program does not crash

Output:

Add/modify dictionary elements

  • Method 1: Add the specified element with the function dict.update()
    Can be used to add, modify elements, and pass in multiple values
dict.update(dict2)#Split Dictionary
dict.update({key:value},{key:value},{key:value})#Add/Modify Elements
#Use of dict.update() function
#Define a dictionary
roman_dict = {'1':'I',2:'II','3':'III','4':'IV'}
#Add element {'5':'V'}
roman_dict.update({'5':'V'})
#Print dictionary after adding elements
print('After adding an element dict: ',roman_dict)
#Modify the value of the first element to one
roman_dict.update({'1':'one'})
#Print modified Dictionaries
print('After modifying the element dict: ',roman_dict)

Output:

  • Method 2: Add at specified location by key value
    Can be used to modify the Value corresponding to a specified key value
dict[key] = value#Add/Modify Elements
#Define a dictionary
roman_dict = {'1':'I',2:'II','3':'III','4':'IV'}
#Add elements at specified locations by key values
roman_dict['5'] = 'V'
print('Added dict: ',roman_dict)
#Modify element value by key value
roman_dict['1'] = 'first'
print('Dictionary modified by key value:',roman_dict)

Output:

  • Method 3: dict.setdefault(key,value) adds a specified element and is not available for modification
    () instead of a dictionary type, a tuple of (key, value) is passed in
dict.setdefault(key,value)#This place is not a dictionary but a tuple and can only be a key-value pair
#Define a dictionary
roman_dict = {'1':'I',2:'II','3':'III','4':'IV'}
#Add an element with dict.setdefault()
roman_dict.setdefault('5','value')
print('Added dict: ',roman_dict)

Output:

Delete operation

Delete the last element

dict.popitrm()#No Passage

Delete the element corresponding to the specified key

Deletes the specified key bit element, pop() returns the value corresponding to the key, and errors occur when none exists

dict.pop(key)

Delete all elements of a dictionary

dict.clear()

Get a set of keys or values, or (key, value) tuples

dict.keys()#key value keyset
dict.values()#value Set
dict.items()#Encapsulate each dictionary element into a tuple and form a new dataset

Posted by noise on Sun, 07 Nov 2021 08:19:32 -0800