current position:Home>Python dictionary query key value pair methods and examples

Python dictionary query key value pair methods and examples

2022-02-01 20:12:33 Parson old bird

Finding is the focus of all our data type learning , Dictionaries are no exception , Find... From different dimensions in different ways , have everything that one expects to find . Let's learn from simple to difficult step by step Query method of dictionary .

1. Use the key to find a single value ****

dict5 = {'name''Tom''age'18'love''python'}
print(dict5['age'])  #  Use the key to find the value 
 Return results :18
 Copy code 

2. Use get() Method to find the value corresponding to the key ****

dict5 = {'name''Tom''age'18'love''python'}
print(dict5.get('age'))   
#  utilize get The function uses the key to find the value , If key There is no return None
print(dict5.get('age'' The default value is '))  
#  If the key doesn't exist , Set to return to default 
 Return results :18
 Copy code 

3. Use setdefault() lookup ****

setdefault and get The function is almost , But if the key doesn't exist , Then the search content is put into the dictionary as a key , And set the default value , Not set to None

dict5 = {'name''Tom''age'18'love''python'}
print(dict5.setdefault('age2'))
age2 non-existent , return None
 Copy code 

4. Query all keys and values and key value pairs ****

dict5 = {'name''Tom''age'18'love''python'}
# keys()  #  Get all keys , Returns a list of 
print(dict5.keys())
# values()  #  Get all values , Returns a list of 
print(dict5.values())
# items()  #  Get all key value pairs , Returns the list of Yuanzu 
print(dict5.items())
 Return results :
dict_keys(['name', 'age', 'love', 'age2'])\
dict_values(['Tom', 18, 'python', None])\
dict_items([('name', 'Tom'), ('age', 18), ('love', 'python'), ('age2', None)])
 Copy code 

From the above returned results, we find that there are three different data types :dict_keys(),dict_values(),dict_items(), Such data cannot be accessed according to the list subscript .

v = dict5.values()
print(v[1])
 Return results :
TypeError: 'dict_values' object is not subscriptable
 Copy code 

  At this time, we can change to Yuanzu and then visit

list_v = list(v)
print(list_v[1])
 Return results :18
 Copy code 

copyright notice
author[Parson old bird],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202012012321095.html

Random recommended