What is a dictionary?

  • In Python, dictionaries, like lists, are mutable sequences, but unlike lists, they are unordered mutable sequences that hold the contents ofKey-value pairsStored in the form of.

The main features of dictionaries are as follows:

  • Read by key name rather than index

  • A dictionary is an unordered collection of arbitrary objects

  • Dictionaries are mutable and can be nested arbitrarily

  • Keys in dictionaries must be unique (the same key is not allowed to appear twice; if it does, the latter value is remembered)

  • Keys in dictionaries must be immutable (keys in dictionaries are immutable, so you can use numbers, strings, or tuples, but not lists)

Dictionary creation and deletion

  • When you define a dictionary, each element contains two partskeyvalue. Take a dictionary of fruit names and prices.
dictionary = {
    'apple': '60'.'pear': '70'
}
Copy the code
  • There are two ways to create an empty dictionary
dictionary = {}

# or

dictionary = dict(a)Copy the code
  • Create dictionaries through mapping functions

    • zip()The iterable () function takes an iterable object as an argument, packs its elements into primitives, and returns a list of those primitives. using*Operator to extract a tuple into a list
    name = ['according to the dream'.'Cold Yee'.'incense setting'.'Diane LAN']
    sign = ['Aquarius'.Sagittarius.'Pisces'.'Gemini']
    dictionary = dict(zip(name, sign))
    print(dictionary)
    
    # {
    #    '依梦': '水瓶座',
    # 'Leng Yee ':' Sagittarius ',
    # 'Shannon ':' Pisces ',
    # 'Dylan ':' Gemini '
    #}
    Copy the code

Creates a dictionary with the given keyword argument

  • Create a dictionary of names and constellations in the form of keyword arguments
dictionary = dict= (according to the dream'Aquarius'Cold dependence =Sagittarius)
Copy the code
  • In Python, it can also be useddictThe object’sfromkeys()Method to create a dictionary with a null value
name_list = ['according to the dream'.'Cold Yee'.'incense setting']
dictionary = dict.fromkeys(name_list)

print(dictionary)
# {' yimeng ': None, 'Leng Yiyi ': None,' Shannon ': None}
Copy the code
  • As with lists and tuples, dictionaries that are no longer needed can also be useddelCommand to delete the entire dictionary. For example, a dictionary that has been defined can be deleted with the following code.
dictionary = { 'according to the dream': None.'Cold Yee': None }
del dictionary

If you only want to delete all elements of the dictionary, you can also use the dictionary object pop() method to delete and return the specified 'key' element
dictionary.clear()
Copy the code