A dictionary is the most flexible built-in data structure type in python other than lists. A list is an ordered association of objects, and a dictionary is an unordered collection of objects.
The difference between the two is that the elements in the dictionary are accessed by key, not by offset.
Dictionaries are identified with "{ }". A dictionary consists of an index (key) and its corresponding value value.
The query rate of the dictionary is higher than that of the list, and the list belongs to linear storage
Each element of the dictionary: key/value key is equivalent to the index in the list Each key of the dictionary: unique Each value of the dictionary: not unique The elements of the dictionary are in no order Dictionaries cannot be manipulated like lists and tuples Immutable types: integers, strings, tuples , and dictionary keys can only store immutable types. If there are two identical keys at the same time, the latter keys will overwrite the former ones mutable types: list, dictionary
#!/usr/bin/python # -*- coding: UTF-8 –*- d = {} d[ ' one ' ] = " This is one " #Add element format to dictionary: dictionary name [key] = value d['2'] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
1. Check
#When the value is obtained by index, if the key does not exist, the default value is returned: None, or the default value can be specified: d.get('key', 'str'), the default value is returned: str print (d.get( ' one1 ' )) # Output the value of the key 'one', if the key does not exist, no error will be reported, return None, it is recommended to use # print(d['one1']) # Output the value of the key 'one', if the key does not exist Then report an error print (d[ ' 2 ' ]) #output the value whose key is '2' print (tinyd) #output the complete dictionary print (tinyd.keys()) #output all keys print (tinyd.values() ) # Output all values print (d.items()) #Get all key-value pairs print ( 'str' in d.keys()) #Check whether the key in the dictionary exists, return true, false print (sorted(d)) #By default, the key name is sorted, and the sorting also requires the same data type, otherwise an error will be reported
2. Increase
d2 = {} d2[ ' hjc ' ] = " boy " #Add element format to dictionary: dictionary name [added key] = value, if the key exists, the value of the key will be modified d.update(d2) #Merge dictionary 2 into dictionary 1 Format: source dictionary.update (the merged dictionary), if the same key exists, the old key will be overwritten after merging d.update({ ' k1 ' : ' v1 ' }) #Another add method print (d ) # {'one': 'This is one', '2': 'This is two', 'hjc': 'boy' , 'k1': 'v1' }
3. Change
d[ ' hjc ' ] = " girl " # The dictionary uses the modified element format: dictionary name [modified key] = value # If the hobby key does not exist, create a new key-value pair, and print, if it exists, do nothing Process and print the existing value d.setdefault( ' hobby ' , ' girl ' ) print (d) # {'one': 'This is one', '2': 'This is two', 'hjc' : 'girl', 'hobby': 'girl' }
4. Delete
del d[ ' hjc ' ] #Delete elements and values in the dictionary format: del dictionary name['deleted key'], if the key does not exist, an error will be reported d.clear() #Clear all the contents of the dictionary and return an empty dictionary print (d.pop( ' key ' )) #Delete the corresponding key and value. If the key does not exist, an error will be reported. dict.pop('key',None) can avoid errors and return None print (d.popitem()) #Randomly delete a group of key-value pairs, useless
5. Other methods
dict1 = dict.fromkeys([ ' host1 ' , ' host2 ' , ' host3 ' ], ' test ' ) # test as a value, and assign it to the previous 3 keys at the same time print (dict1) # {'host1': 'test' , 'host2': 'test', 'host3': 'test'} dict1 = dict.fromkeys([ ' host1 ' , ' host2 ' , ' host3 ' ], [ ' test1 ' , ' test2 ']) #value as a list, assigned to the first 3 keys as a value print(dict1) # {'host1': ['test1', 'test2'], 'host2': ['test1', 'test2'], 'host3': ['test1', 'test2']}
#Take key in a loop: for i in tinyd: print (i) #Loop through key-value pairs; #Method 1: (recommended, most efficient) for i in tinyd: print (i, tinyd[i]) ''' name john code 6734 dept sales ''' #Method 2: for k, v in tinyd.items(): # items output key-value pairs by default, set variables here, assign key to k, value to v print (k, v) ''' name john code 6734 dept sales ''' # 法3: new_dic = dict(enumerate(tinyd)) print(new_dic) # {0: 'name', 1: 'code', 2: 'dept'}